@nexus-cross/crossx-sdk-core 2.2.4 → 2.3.0-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/confirmation/BridgeConfirmationAdapter.d.ts +1 -0
- package/dist/adapters/confirmation/BridgeConfirmationAdapter.d.ts.map +1 -1
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +1 -0
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/adapters/wallet/RNBridgeWalletProviderAdapter.d.ts +13 -1
- package/dist/adapters/wallet/RNBridgeWalletProviderAdapter.d.ts.map +1 -1
- package/dist/core/i18n/messages.en.d.ts.map +1 -1
- package/dist/core/i18n/messages.ko.d.ts.map +1 -1
- package/dist/core/i18n/types.d.ts +4 -0
- package/dist/core/i18n/types.d.ts.map +1 -1
- package/dist/core/ports/ConfirmationPort.d.ts +5 -0
- package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
- package/dist/core/services/RNBridgeBootstrapService.d.ts +19 -0
- package/dist/core/services/RNBridgeBootstrapService.d.ts.map +1 -1
- package/dist/core/types/rn-bridge.d.ts +9 -0
- package/dist/core/types/rn-bridge.d.ts.map +1 -1
- package/dist/core/usecases/SignInUseCase.d.ts +8 -1
- package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
- package/dist/crossx.global +716 -258
- package/dist/index.cjs +720 -262
- package/dist/index.js +2229 -1538
- package/dist/sdk/CROSSxSDK.d.ts +16 -1
- package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
- package/dist/sdk/factory.d.ts.map +1 -1
- package/dist/sdk/services/WalletCreationService.d.ts +1 -0
- package/dist/sdk/services/WalletCreationService.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
"use strict";var
|
|
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:"이전에 이 게임에서 사용한 지갑을
|
|
1
|
+
"use strict";var cs=Object.defineProperty;var ls=(s,e,r)=>e in s?cs(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var O=(s,e,r)=>ls(s,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const at=require("jose");var h=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(h||{});class f extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,f.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}var Le=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(Le||{});const ds={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},fr=["crossx","io.metamask","com.binance.wallet"];function xr(s){return ds[s]??s}function us(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...fr]:[]}const st={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},hs=Object.fromEntries(Object.entries(st).map(([s,e])=>[s,e.caipId])),ps=new Map(Object.values(st).map(s=>[s.caipId,s]));new Map(Object.values(st).map(s=>[s.chainId,s]));const _s={symbol:"",decimals:18};function ct(s){var e;return((e=ps.get(s))==null?void 0:e.nativeCurrency)??_s}class gr{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 f(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new f(h.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(n=>n(...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 pe=null;function Mt(s){pe=s}const d={info(...s){if(pe){pe.log(...s);return}console.log(...s)},log(...s){if(pe){pe.log(...s);return}},warn(...s){if(pe){pe.warn(...s);return}},error(...s){if(pe){pe.error(...s);return}}},fs={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
|
+
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:"다시 로그인"},wr={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",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:"CROSS Wallet",login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select 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
|
|
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:"다시 로그인"},wr={confirm:"Confirm",cancel:"Cancel",close:"Close",signature_requesting:" is requesting a Signature",signature_warning:"After you sign, changes or cancellations are not possible.",signature_sign_button:"Sign",sign_message_title:"Sign Message",sign_typed_data_title:"Sign Data",sign_transaction_title:"Sign Transaction",send_transaction_title:"Send Transaction",send_tx_permission_text:" wants your permission to approve the following transaction.",send_tx_approve_button:"Approve",send_tx_confirm_button:"Confirm",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:"CROSS Wallet",login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
|
|
5
5
|
|
|
6
|
-
For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},fs={ko:_s,en:wr};function xe(s="en",e){return fs[s]??wr}function gs(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Ft="crossx_access_token",Ut="crossx_refresh_token",Ht="crossx_user_info",rt=class rt{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`}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 hasStoredRNBridgeSession(){if(!await this.hasValidStoredAccessToken())return!1;try{return!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN)}catch{return!1}}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new f(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=gs(this.getLocale()),c=`${o}${i}`,l=c.includes("?")?"&":"?",u=`${c}${l}locale=${a}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const p=await this.oauth.openAuth({authUrl:u,expectedOrigin:new URL(o).origin});r=p.token,t=p.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new f(h.OAUTH_POPUP_BLOCKED,i):new f(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const p=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=p.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new f(h.AUTH_FAILED,"Access token 검증 실패");const p=u.payload;r={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new f(h.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:g}=await this.exchangeFirebaseToken(e,u);let _,x,y;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),x=(i=A.firebase)==null?void 0:i.sign_in_provider;const R=((o=A.firebase)==null?void 0:o.identities)??{};y=A.email??((a=R.email)==null?void 0:a[0]),x==="google.com"?_=(c=R["google.com"])==null?void 0:c[0]:x==="apple.com"&&(_=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!_,"email:",y??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const A=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const R=await this.crypto.verifyJWT(p);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const k=R.payload,L=k.email??y??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",k.email??"(없음)","/ Firebase JWT:",y??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:k.sub,email:L,signInProvider:x,providerSub:_},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??r,signInProvider:x,providerSub:_},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const v=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,v),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new f(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new f(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new f(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof f&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=rt.REFRESH_RELOGIN_CODES.has(c.code);throw new f(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new f(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof f&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof f&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Ht);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(Ft);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Ut);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Ht),await this.storage.remove(Ft),await this.storage.remove(Ut),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof f&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof f&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};rt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let mt=rt;class xs{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class ws{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new f(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class It{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class ms{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new f(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class ys{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function bs(){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 fe{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await fe.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=fe.getBridge(),!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new f(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=bs(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new f(h.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),walletAddress:n.walletAddress,walletName:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new f(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){var e;if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not activated");try{const r=await this.bridge.requestFirebaseIdToken(),t=(r.expiresAt-Date.now())/1e3;if(t<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return r}catch(r){if(r instanceof f)throw r;const t=r instanceof Error?r.message:String(r);throw t.includes("USER_REJECTED")||t.toLowerCase().includes("rejected")?new f(h.USER_REJECTED,"Firebase ID token request rejected by user",r):(d.error("[RNBridge] Firebase token request failed",r),new f(h.AUTH_FAILED,"Firebase token request failed",r))}}async requestFreshFirebaseIdToken(){var e;if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not activated");try{const r=await this.bridge.requestFreshFirebaseIdToken();if((r.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof f?r:(d.error("[RNBridge] Fresh Firebase token request failed",r),new f(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",r))}}getContext(){return this.context}isActive(){var t;return!(!((t=this.context)!=null&&t.isActivated)||Date.now()-this.context.activatedAt>this.context.absoluteTtlMs)}}const De={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 vs(s){const e=s.environment;return e&&e in De?De[e]:null}function mr(){try{if(typeof __CROSSX_CONFIG__<"u"){const s=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=vs(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in De)return De[s]}catch{}return De.production}const Ss=2e3,Wt=6e4,Es=1e3,As=1e4,Is="0x77359400",Gt="0x3B9ACA00",qt=130,Tt=6,Kt=18,Vt=3e4,Ts=5*60*1e3,ks=30*1e3,Xe=100,Rs="crossx-sdk-js/2.2.4";function yr(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Ns(s,e=Tt){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Kt),n=r/t,o=(r%t).toString().padStart(Kt,"0"),a=yr(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function qe(s,e,r,t=Tt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=yr(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Os(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==qt)throw new f(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${qt} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Cs(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Ps(s,e){const r=Ls(e);if(s==="0"){if(r!==void 0&&r!==0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Ls(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Pe{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new f(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=xe(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof f){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Pe.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof f&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=xe(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.session_alert_title,message:l.alert_session_expired,email:u?this.deps.maskEmail(u,l.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=xe(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof f){if(t=Pe.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof f&&(t=Pe.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===h.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Pe.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Ds{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new f(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function $s(s){return s==="google"||s==="apple"}class Bs{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=$s(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=xe(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=xe(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof f&&r.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof f&&r.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof f)||r.code!==h.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new f(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new f(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Ms{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const p=o.find(g=>g.address.toLowerCase()===r.toLowerCase());p?c=p:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(p=>p.index===e)??o[0]:c=o[0];l?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const u=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,u?{walletName:t}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Fs{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!p){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(p.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const g=p.pinStatus;if(o=g.maxAttempts,i=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const _=g.lockExpiresAt*1e3,x=Math.max(1,Math.round((_-Date.now())/1e3)),y=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${y}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,y),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof f))throw p;if(p.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=xe(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:_?this.deps.maskEmail(_,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const g=p.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((g==null?void 0:g.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((_-Date.now())/1e3)),y=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,y),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof f&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof f&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=xe(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:g?this.deps.maskEmail(g,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const y=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",y.address),y}catch(y){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",y),y}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Us{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,g]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=g;if(_){const x=Gt;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(x)).toString(16)}`,c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Is,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Gt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Hs{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new f(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof f)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Ws(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class Gs{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Ws((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class qs{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new f(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Ks{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new f(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new f(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Vs{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return r==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof f&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function zt(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class zs{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new f(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=zt(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof f?c:new f(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(zt(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new f(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof f?i:new f(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof f&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:h.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:h.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:h.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new f(n.code,n.message)}}function lt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const ke=class ke extends ys{constructor(e,r,t,n,i,o,a,c,l,u,p){var g,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&Mt(e.logger),this.confirmation=l,this.pinStore=p??new It,this.stateManager=new Gs({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:y,walletName:v})=>{const A={address:x,index:y};v!==void 0&&(A.walletName=v),this.emit("addressChanged",A)},emitAuthChanged:({isAuthenticated:x,address:y,userId:v})=>{this.emit("authChanged",{isAuthenticated:x,address:y,userId:v})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:ke.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Pe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:lt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Ds({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Ms({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,y,v)=>this.setActiveWallet(x,y,v)}),this.migrationOrchestrator=new Fs({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,y)=>this.migrateWalletUseCase.execute(x,y),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:lt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new Us({getActiveAddress:()=>this.address,estimateGas:(x,y)=>this.estimateGas(x,y),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,y,v)=>this.jsonRpc.call(x,y,v)}),this.signatureVerifier=new Hs(this.crypto),this.addressResolverService=new qs({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Ks({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Vs({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,y)=>this.setActiveWallet(x,y)}),this.tokenHistoryService=new zs({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Bs({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:x=>{this._isRecoveringSession=x},setAuthenticated:x=>{this.authenticated=x},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:x=>this.signInUseCase.execute(x),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:x=>this.confirmation.showSessionAlert(x),clearAuthState:()=>this.clearAuthState(),applyAuthResult:x=>this.applyAuthResult(x),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:lt}),this.chainRegistry=u,this.jsonRpc=new ms(u,i),this.signInUseCase=new mt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new xs(this.internalConfig,t,c),this.migrateWalletUseCase=new ws(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.2.4 초기화 중..."),this.confirmation.setMessages(xe(this._config.locale));try{const n=mr();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(ke.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),u=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,u?{walletName:u}:void 0);else try{await this.loadWalletAfterAuth(o,a,u)}catch(p){if(!(p instanceof f&&p.code===h.PIN_CANCELLED))throw p;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v2.2.4 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new f(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!fe.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new fe({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.2.4",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();return this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"}),await this.signInUseCase.hasValidStoredAccessToken()?(await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 — native sign delegation 활성")),null):(d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null)}catch(e){return d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof f&&r.code===h.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new f(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFreshFirebaseIdToken()}catch(e){throw d.error("[CROSSx] Fresh Firebase token request failed:",e),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return fe.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(t!=null&&t.success)return t}let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:ds(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new f(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof f&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&this.applyAuthResult(r)}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",t)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof f&&t.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=fe.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new f(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof f&&r.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof f?r:new f(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof f?e:new f(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof f?r:new f(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(xe(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new f(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Ps(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Os(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(ke.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return Cs(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return p.txHash??p.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Rs).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??Es,i=As,o=t.timeoutMs??Wt,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new f(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var y,v;if(this._isAuthenticatedViaRNBridge){const A=fe.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((y=this._config.receiptPolling)==null?void 0:y.intervalMs)??Ss,l=i??((v=this._config.receiptPolling)==null?void 0:v.timeoutMs)??Wt,u=ct(e),p=r.from??"";let g,_;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{g=A;const R=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),k=r.value?BigInt(r.value):0n,L=qe(r.value,u.symbol,u.decimals,this._config.displayDecimals),D=qe("0x"+R.toString(16),u.symbol,u.decimals,this._config.displayDecimals),V=qe("0x"+(k+R).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:L,fees:D,total:V,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(_=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:p,to:r.to,amount:qe(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},x),_)throw _;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new f(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof f?n:new f(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new f(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Ns(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new xr(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof f)throw n;const i=n instanceof Error?n.message:String(n);throw new f(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=fe.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated){d.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Mt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};ke.WALLET_PREF_KEY="wallet_preference",ke.OFFCHAIN_CHAIN_ID="0";let Je=ke;class js{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const dt="crossx-sdk",Ys=1,ue="data",Ae="keys",Ke="aes-primary",Xs=12;class jt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,Ys);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ue)||i.createObjectStore(ue),i.objectStoreNames.contains(Ae)||i.createObjectStore(Ae)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ae,Ke);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(Ae,Ke,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===dt)return null;try{const e=await this.openDB(dt),r=e.transaction([Ae,ue],"readonly"),t=r.objectStore(Ae).get(Ke),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(ue).getAll(),o=r.objectStore(ue).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ae,Ke,n);for(let l=0;l<c.length;l++)await this.idbPut(ue,String(c[l]),a[l]);return indexedDB.deleteDatabase(dt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Xs);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(ue,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(ue,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ue,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(ue)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function kt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function me(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function X(s,e,r=""){const t=kt(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function br(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");me(s.outputLen),me(s.blockLen)}function Be(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function vr(s,e){X(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Js(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Me(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function ut(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function he(s,e){return s<<32-e|s>>>e}const Zs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Qs(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function en(s){for(let e=0;e<s.length;e++)s[e]=Qs(s[e]);return s}const Yt=Zs?s=>s:en,Sr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",tn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ge(s){if(X(s),Sr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=tn[s[r]];return e}const pe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xt(s){if(s>=pe._0&&s<=pe._9)return s-pe._0;if(s>=pe.A&&s<=pe.F)return s-(pe.A-10);if(s>=pe.a&&s<=pe.f)return s-(pe.a-10)}function Ze(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Sr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=Xt(s.charCodeAt(i)),a=Xt(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Se(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];X(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function Er(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Ar(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const rn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function sn(s,e,r){return s&e^~s&r}function nn(s,e,r){return s&e^s&r^e&r}class on{constructor(e,r,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){Be(this),X(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=ut(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Be(this),vr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Me(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)r[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=ut(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ve=BigInt(2**32-1),Jt=BigInt(32);function an(s,e=!1){return e?{h:Number(s&Ve),l:Number(s>>Jt&Ve)}:{h:Number(s>>Jt&Ve)|0,l:Number(s&Ve)|0}}function cn(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=an(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const ln=(s,e,r)=>s<<r|e>>>32-r,dn=(s,e,r)=>e<<r|s>>>32-r,un=(s,e,r)=>e<<r-32|s>>>64-r,hn=(s,e,r)=>s<<r-32|e>>>64-r,pn=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),be=new Uint32Array(64);class _n extends on{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let p=0;p<16;p++,r+=4)be[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const g=be[p-15],_=be[p-2],x=he(g,7)^he(g,18)^g>>>3,y=he(_,17)^he(_,19)^_>>>10;be[p]=y+be[p-7]+x+be[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const g=he(a,6)^he(a,11)^he(a,25),_=u+g+sn(a,c,l)+pn[p]+be[p]|0,y=(he(t,2)^he(t,13)^he(t,22))+nn(t,n,i)|0;u=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+y|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){Me(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Me(this.buffer)}}class fn extends _n{constructor(){super(32);P(this,"A",ye[0]|0);P(this,"B",ye[1]|0);P(this,"C",ye[2]|0);P(this,"D",ye[3]|0);P(this,"E",ye[4]|0);P(this,"F",ye[5]|0);P(this,"G",ye[6]|0);P(this,"H",ye[7]|0)}}const gn=Er(()=>new fn,rn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Rt=BigInt(0),yt=BigInt(1);function Qe(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Ir(s){if(typeof s=="bigint"){if(!Ye(s))throw new Error("positive bigint expected, got "+s)}else me(s);return s}function ze(s){const e=Ir(s).toString(16);return e.length&1?"0"+e:e}function Tr(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Rt:BigInt("0x"+s)}function nt(s){return Tr(Ge(s))}function kr(s){return Tr(Ge(xn(X(s)).reverse()))}function Nt(s,e){me(e),s=Ir(s);const r=Ze(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Rr(s,e){return Nt(s,e).reverse()}function xn(s){return Uint8Array.from(s)}const Ye=s=>typeof s=="bigint"&&Rt<=s;function wn(s,e,r){return Ye(s)&&Ye(e)&&Ye(r)&&e<=s&&s<r}function mn(s,e,r,t){if(!wn(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function yn(s){let e;for(e=0;s>Rt;s>>=yt,e+=1);return e}const Ot=s=>(yt<<BigInt(s))-yt;function bn(s,e,r){if(me(s,"hashLen"),me(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=v=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},g=(...v)=>r(l,Se(c,...v)),_=(v=n)=>{l=g(i,v),c=g(),v.length!==0&&(l=g(o,v),c=g())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let v=0;const A=[];for(;v<e;){c=g();const R=c.slice();A.push(R),v+=c.length}return Se(...A)};return(v,A)=>{p(),_(v);let R;for(;!(R=A(x()));)_();return p(),R}}function Ct(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function Zt(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),re=BigInt(1),Re=BigInt(2),Nr=BigInt(3),Or=BigInt(4),Cr=BigInt(5),vn=BigInt(7),Pr=BigInt(8),Sn=BigInt(9),Lr=BigInt(16);function le(s,e){const r=s%e;return r>=se?r:e+r}function oe(s,e,r){let t=s;for(;e-- >se;)t*=t,t%=r;return t}function Qt(s,e){if(s===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let r=le(s,e),t=e,n=se,i=re;for(;r!==se;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==re)throw new Error("invert: does not exist");return le(n,e)}function Pt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Dr(s,e){const r=(s.ORDER+re)/Or,t=s.pow(e,r);return Pt(s,t,e),t}function En(s,e){const r=(s.ORDER-Cr)/Pr,t=s.mul(e,Re),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Re),n),a=s.mul(i,s.sub(o,s.ONE));return Pt(s,a,e),a}function An(s){const e=it(s),r=$r(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+vn)/Lr;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),g=a.mul(l,i),_=a.eql(a.sqr(u),c),x=a.eql(a.sqr(p),c);l=a.cmov(l,u,_),u=a.cmov(g,p,x);const y=a.eql(a.sqr(u),c),v=a.cmov(l,u,y);return Pt(a,v,c),v}}function $r(s){if(s<Nr)throw new Error("sqrt is not defined for small field");let e=s-re,r=0;for(;e%Re===se;)e/=Re,r++;let t=Re;const n=it(s);for(;er(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Dr;let i=n.pow(t,e);const o=(e+re)/Re;return function(c,l){if(c.is0(l))return l;if(er(c,l)!==1)throw new Error("Cannot find square root");let u=r,p=c.mul(c.ONE,i),g=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let x=1,y=c.sqr(g);for(;!c.eql(y,c.ONE);)if(x++,y=c.sqr(y),x===u)throw new Error("Cannot find square root");const v=re<<BigInt(u-x-1),A=c.pow(p,v);u=x,p=c.sqr(A),g=c.mul(g,p),_=c.mul(_,A)}return _}}function In(s){return s%Or===Nr?Dr:s%Pr===Cr?En:s%Lr===Sn?An(s):$r(s)}const Tn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function kn(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Tn.reduce((t,n)=>(t[n]="function",t),e);return Ct(s,r),s}function Rn(s,e,r){if(r<se)throw new Error("invalid exponent, negatives unsupported");if(r===se)return s.ONE;if(r===re)return e;let t=s.ONE,n=e;for(;r>se;)r&re&&(t=s.mul(t,n)),n=s.sqr(n),r>>=re;return t}function Br(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function er(s,e){const r=(s.ORDER-re)/Re,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Nn(s,e){e!==void 0&&me(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class On{constructor(e,r={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",se);P(this,"ONE",re);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Nn(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return le(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return le(e*e,this.ORDER)}add(e,r){return le(e+r,this.ORDER)}sub(e,r){return le(e-r,this.ORDER)}mul(e,r){return le(e*r,this.ORDER)}pow(e,r){return Rn(this,e,r)}div(e,r){return le(e*Qt(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Qt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=In(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Rr(e,this.BYTES):Nt(e,this.BYTES)}fromBytes(e,r=!1){X(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?kr(e):nt(e);if(a&&(c=le(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Br(this,e)}cmov(e,r,t){return t?r:e}}function it(s,e={}){return new On(s,e)}function Mr(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Fr(s){const e=Mr(s);return e+Math.ceil(e/2)}function Cn(s,e,r=!1){X(s);const t=s.length,n=Mr(e),i=Fr(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?kr(s):nt(s),a=le(o,e-re)+re;return r?Rr(a,n):Nt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Fe=BigInt(0),Ne=BigInt(1);function et(s,e){const r=e.negate();return s?r:e}function tr(s,e){const r=Br(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Ur(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function ht(s,e){Ur(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Ot(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function rr(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=Ne);const l=e*t,u=l+Math.abs(a)-1,p=a===0,g=a<0,_=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:g,isNegF:_,offsetF:l}}const pt=new WeakMap,Hr=new WeakMap;function _t(s){return Hr.get(s)||1}function sr(s){if(s!==Fe)throw new Error("invalid wNAF")}class Pn{constructor(e,r){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Fe;)r&Ne&&(t=t.add(n)),n=n.double(),r>>=Ne;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=ht(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=ht(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:g,offsetF:_}=rr(t,a,o);t=c,u?i=i.add(et(g,r[_])):n=n.add(et(p,r[l]))}return sr(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=ht(e,this.bits);for(let o=0;o<i.windows&&t!==Fe;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=rr(t,o,i);if(t=a,!l){const p=r[c];n=n.add(u?p.negate():p)}}return sr(t),n}getPrecomputes(e,r,t){let n=pt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),pt.set(r,n))),n}cached(e,r,t){const n=_t(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=_t(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Ur(r,this.bits),Hr.set(e,r),pt.delete(e)}hasCache(e){return _t(e)!==1}}function Ln(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Fe||t>Fe;)r&Ne&&(i=i.add(n)),t&Ne&&(o=o.add(n)),n=n.double(),r>>=Ne,t>>=Ne;return{p1:i,p2:o}}function nr(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return kn(e),e}else return it(s,{isLE:r})}function Dn(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Fe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=nr(e.p,r.Fp,t),i=nr(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function $n(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Wr{constructor(e,r){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(br(e),X(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Me(n)}update(e){return Be(this),this.iHash.update(e),this}digestInto(e){Be(this),X(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gr=(s,e,r)=>new Wr(s,e).update(r).digest();Gr.create=(s,e)=>new Wr(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ir=(s,e)=>(s+(s>=0?e:-e)/qr)/e;function Bn(s,e,r){const[[t,n],[i,o]]=e,a=ir(o*s,r),c=ir(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const p=l<ge,g=u<ge;p&&(l=-l),g&&(u=-u);const _=Ot(Math.ceil(yn(r)/2))+$e;if(l<ge||l>=_||u<ge||u>=_)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:g,k2:u}}function bt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function ft(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return Qe(r.lowS,"lowS"),Qe(r.prehash,"prehash"),r.format!==void 0&&bt(r.format),r}class Mn extends Error{constructor(e=""){super(e)}}const ve={Err:Mn,_tlv:{encode:(s,e)=>{const{Err:r}=ve;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=ze(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?ze(n.length/2|128):"";return ze(s)+i+n+e},decode(s,e){const{Err:r}=ve;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=ve;if(s<ge)throw new e("integer: negative integers are not allowed");let r=ze(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=ve;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return nt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=ve,n=X(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=ve,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},ge=BigInt(0),$e=BigInt(1),qr=BigInt(2),je=BigInt(3),Fn=BigInt(4);function Un(s,e={}){const r=Dn("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Ct(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Vr(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(H,m,w){const{x:T,y:O}=m.toAffine(),F=t.toBytes(T);if(Qe(w,"isCompressed"),w){u();const $=!t.isOdd(O);return Se(Kr($),F)}else return Se(Uint8Array.of(4),F,t.toBytes(O))}function g(H){X(H,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,T=H.length,O=H[0],F=H.subarray(1);if(T===m&&(O===2||O===3)){const $=t.fromBytes(F);if(!t.isValid($))throw new Error("bad point: is not on curve, wrong x");const M=y($);let C;try{C=t.sqrt(M)}catch(E){const N=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}u();const W=t.isOdd(C);return(O&1)===1!==W&&(C=t.neg(C)),{x:$,y:C}}else if(T===w&&O===4){const $=t.BYTES,M=t.fromBytes(F.subarray(0,$)),C=t.fromBytes(F.subarray($,$*2));if(!v(M,C))throw new Error("bad point: is not on curve");return{x:M,y:C}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${w}`)}const _=e.toBytes||p,x=e.fromBytes||g;function y(H){const m=t.sqr(H),w=t.mul(m,H);return t.add(t.add(w,t.mul(H,i.a)),i.b)}function v(H,m){const w=t.sqr(m),T=y(H);return t.eql(w,T)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,je),Fn),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,R)))throw new Error("bad curve params: a or b");function k(H,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${H}`);return m}function L(H){if(!(H instanceof J))throw new Error("Weierstrass Point expected")}function D(H){if(!c||!c.basises)throw new Error("no endo");return Bn(H,c.basises,n.ORDER)}const V=Zt((H,m)=>{const{X:w,Y:T,Z:O}=H;if(t.eql(O,t.ONE))return{x:w,y:T};const F=H.is0();m==null&&(m=F?t.ONE:t.inv(O));const $=t.mul(w,m),M=t.mul(T,m),C=t.mul(O,m);if(F)return{x:t.ZERO,y:t.ZERO};if(!t.eql(C,t.ONE))throw new Error("invZ was invalid");return{x:$,y:M}}),Q=Zt(H=>{if(H.is0()){if(e.allowInfinityPoint&&!t.is0(H.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=H.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!v(m,w))throw new Error("bad point: equation left != right");if(!H.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function q(H,m,w,T,O){return w=new J(t.mul(w.X,H),w.Y,w.Z),m=et(T,m),w=et(O,w),m.add(w)}const B=class B{constructor(m,w,T){P(this,"X");P(this,"Y");P(this,"Z");this.X=k("x",m),this.Y=k("y",w,!0),this.Z=k("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:T}=m||{};if(!m||!t.isValid(w)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof B)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(T)?B.ZERO:new B(w,T,t.ONE)}static fromBytes(m){const w=B.fromAffine(x(X(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return B.fromBytes(Ze(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return G.createCache(this,m),w||this.multiply(je),this}assertValidity(){Q(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){L(m);const{X:w,Y:T,Z:O}=this,{X:F,Y:$,Z:M}=m,C=t.eql(t.mul(w,M),t.mul(F,O)),W=t.eql(t.mul(T,M),t.mul($,O));return C&&W}negate(){return new B(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,T=t.mul(w,je),{X:O,Y:F,Z:$}=this;let M=t.ZERO,C=t.ZERO,W=t.ZERO,b=t.mul(O,O),E=t.mul(F,F),N=t.mul($,$),I=t.mul(O,F);return I=t.add(I,I),W=t.mul(O,$),W=t.add(W,W),M=t.mul(m,W),C=t.mul(T,N),C=t.add(M,C),M=t.sub(E,C),C=t.add(E,C),C=t.mul(M,C),M=t.mul(I,M),W=t.mul(T,W),N=t.mul(m,N),I=t.sub(b,N),I=t.mul(m,I),I=t.add(I,W),W=t.add(b,b),b=t.add(W,b),b=t.add(b,N),b=t.mul(b,I),C=t.add(C,b),N=t.mul(F,$),N=t.add(N,N),b=t.mul(N,I),M=t.sub(M,b),W=t.mul(N,E),W=t.add(W,W),W=t.add(W,W),new B(M,C,W)}add(m){L(m);const{X:w,Y:T,Z:O}=this,{X:F,Y:$,Z:M}=m;let C=t.ZERO,W=t.ZERO,b=t.ZERO;const E=i.a,N=t.mul(i.b,je);let I=t.mul(w,F),U=t.mul(T,$),K=t.mul(O,M),j=t.add(w,T),z=t.add(F,$);j=t.mul(j,z),z=t.add(I,U),j=t.sub(j,z),z=t.add(w,O);let Y=t.add(F,M);return z=t.mul(z,Y),Y=t.add(I,K),z=t.sub(z,Y),Y=t.add(T,O),C=t.add($,M),Y=t.mul(Y,C),C=t.add(U,K),Y=t.sub(Y,C),b=t.mul(E,z),C=t.mul(N,K),b=t.add(C,b),C=t.sub(U,b),b=t.add(U,b),W=t.mul(C,b),U=t.add(I,I),U=t.add(U,I),K=t.mul(E,K),z=t.mul(N,z),U=t.add(U,K),K=t.sub(I,K),K=t.mul(E,K),z=t.add(z,K),I=t.mul(U,z),W=t.add(W,I),I=t.mul(Y,z),C=t.mul(j,C),C=t.sub(C,I),I=t.mul(j,U),b=t.mul(Y,b),b=t.add(b,I),new B(C,W,b)}subtract(m){return this.add(m.negate())}is0(){return this.equals(B.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,O;const F=$=>G.cached(this,$,M=>tr(B,M));if(w){const{k1neg:$,k1:M,k2neg:C,k2:W}=D(m),{p:b,f:E}=F(M),{p:N,f:I}=F(W);O=E.add(I),T=q(w.beta,b,N,$,C)}else{const{p:$,f:M}=F(m);T=$,O=M}return tr(B,[T,O])[0]}multiplyUnsafe(m){const{endo:w}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===ge||T.is0())return B.ZERO;if(m===$e)return T;if(G.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:F,k2neg:$,k2:M}=D(m),{p1:C,p2:W}=Ln(B,T,F,M);return q(w.beta,C,W,O,$)}else return G.unsafe(T,m)}toAffine(m){return V(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===$e?!0:m?m(B,this):G.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===$e?this:m?m(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return Qe(m,"isCompressed"),this.assertValidity(),_(B,this,m)}toHex(m=!0){return Ge(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(B,"BASE",new B(i.Gx,i.Gy,t.ONE)),P(B,"ZERO",new B(t.ZERO,t.ONE,t.ZERO)),P(B,"Fp",t),P(B,"Fn",n);let J=B;const te=n.BITS,G=new Pn(J,e.endo?Math.ceil(te/2):te);return J.BASE.precompute(8),J}function Kr(s){return Uint8Array.of(s?2:3)}function Vr(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Hn(s,e={}){const{Fn:r}=s,t=e.randomBytes||Ar,n=Object.assign(Vr(s.Fp,r),{seed:Fr(r.ORDER)});function i(_){try{const x=r.fromBytes(_);return r.isValidNot0(x)}catch{return!1}}function o(_,x){const{publicKey:y,publicKeyUncompressed:v}=n;try{const A=_.length;return x===!0&&A!==y||x===!1&&A!==v?!1:!!s.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return Cn(X(_,n.seed,"seed"),r.ORDER)}function c(_,x=!0){return s.BASE.multiply(r.fromBytes(_)).toBytes(x)}function l(_){const{secretKey:x,publicKey:y,publicKeyUncompressed:v}=n;if(!kt(_)||"_lengths"in r&&r._lengths||x===y)return;const A=X(_,void 0,"key").length;return A===y||A===v}function u(_,x,y=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const v=r.fromBytes(_);return s.fromBytes(x).multiply(v).toBytes(y)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=$n(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:g,Point:s,utils:p,lengths:n})}function Wn(s,e,r={}){br(e),Ct(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Ar,n=r.hmac||((m,w)=>Gr(e,m,w)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:_}=Hn(s,r),x={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},y=a*qr<i.ORDER;function v(m){const w=a>>$e;return m>w}function A(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function R(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(m,w){bt(w);const T=_.signature,O=w==="compact"?T:w==="recovered"?T+1:void 0;return X(m,O)}class L{constructor(w,T,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=A("r",w),this.s=A("s",T),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,T=x.format){k(w,T);let O;if(T==="der"){const{r:C,s:W}=ve.toSig(X(w));return new L(C,W)}T==="recovered"&&(O=w[0],T="compact",w=w.subarray(1));const F=_.signature/2,$=w.subarray(0,F),M=w.subarray(F,F*2);return new L(o.fromBytes($),o.fromBytes(M),O)}static fromHex(w,T){return this.fromBytes(Ze(w),T)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new L(this.r,this.s,w)}recoverPublicKey(w){const{r:T,s:O}=this,F=this.assertRecovery(),$=F===2||F===3?T+a:T;if(!i.isValid($))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes($),C=s.fromBytes(Se(Kr((F&1)===0),M)),W=o.inv($),b=V(X(w,void 0,"msgHash")),E=o.create(-b*W),N=o.create(O*W),I=s.BASE.multiplyUnsafe(E).add(C.multiplyUnsafe(N));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return v(this.s)}toBytes(w=x.format){if(bt(w),w==="der")return Ze(ve.hexFromSig(this));const{r:T,s:O}=this,F=o.toBytes(T),$=o.toBytes(O);return w==="recovered"?(R(),Se(Uint8Array.of(this.assertRecovery()),F,$)):Se(F,$)}toHex(w){return Ge(this.toBytes(w))}}const D=r.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const T=nt(w),O=w.length*8-c;return O>0?T>>BigInt(O):T},V=r.bits2int_modN||function(w){return o.create(D(w))},Q=Ot(c);function q(m){return mn("num < 2^"+c,m,ge,Q),o.toBytes(m)}function J(m,w){return X(m,void 0,"message"),w?X(e(m),void 0,"prehashed message"):m}function te(m,w,T){const{lowS:O,prehash:F,extraEntropy:$}=ft(T,x);m=J(m,F);const M=V(m),C=o.fromBytes(w);if(!o.isValidNot0(C))throw new Error("invalid private key");const W=[q(C),q(M)];if($!=null&&$!==!1){const I=$===!0?t(_.secretKey):$;W.push(X(I,void 0,"extraEntropy"))}const b=Se(...W),E=M;function N(I){const U=D(I);if(!o.isValidNot0(U))return;const K=o.inv(U),j=s.BASE.multiply(U).toAffine(),z=o.create(j.x);if(z===ge)return;const Y=o.create(K*o.create(E+z*C));if(Y===ge)return;let Ee=(j.x===z?0:2)|Number(j.y&$e),Bt=Y;return O&&v(Y)&&(Bt=o.neg(Y),Ee^=1),new L(z,Bt,y?void 0:Ee)}return{seed:b,k2sig:N}}function G(m,w,T={}){const{seed:O,k2sig:F}=te(m,w,T);return bn(e.outputLen,o.BYTES,n)(O,F).toBytes(T.format)}function B(m,w,T,O={}){const{lowS:F,prehash:$,format:M}=ft(O,x);if(T=X(T,void 0,"publicKey"),w=J(w,$),!kt(m)){const C=m instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+C)}k(m,M);try{const C=L.fromBytes(m,M),W=s.fromBytes(T);if(F&&C.hasHighS())return!1;const{r:b,s:E}=C,N=V(w),I=o.inv(E),U=o.create(N*I),K=o.create(b*I),j=s.BASE.multiplyUnsafe(U).add(W.multiplyUnsafe(K));return j.is0()?!1:o.create(j.x)===b}catch{return!1}}function H(m,w,T={}){const{prehash:O}=ft(T,x);return w=J(w,O),L.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:_,Point:s,sign:G,verify:B,recoverPublicKey:H,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Lt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Gn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},or=BigInt(2);function qn(s){const e=Lt.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,p=oe(u,r,e)*u%e,g=oe(p,r,e)*u%e,_=oe(g,or,e)*l%e,x=oe(_,n,e)*_%e,y=oe(x,i,e)*x%e,v=oe(y,a,e)*y%e,A=oe(v,c,e)*v%e,R=oe(A,a,e)*y%e,k=oe(R,r,e)*u%e,L=oe(k,o,e)*x%e,D=oe(L,t,e)*l%e,V=oe(D,or,e);if(!vt.eql(vt.sqr(V),s))throw new Error("Cannot find square root");return V}const vt=it(Lt.p,{sqrt:qn}),Kn=Un(Lt,{Fp:vt,endo:Gn}),Vn=Wn(Kn,gn),zn=BigInt(0),Ue=BigInt(1),jn=BigInt(2),Yn=BigInt(7),Xn=BigInt(256),Jn=BigInt(113),zr=[],jr=[],Yr=[];for(let s=0,e=Ue,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],zr.push(2*(5*t+r)),jr.push((s+1)*(s+2)/2%64);let n=zn;for(let i=0;i<7;i++)e=(e<<Ue^(e>>Yn)*Jn)%Xn,e&jn&&(n^=Ue<<(Ue<<BigInt(i))-Ue);Yr.push(n)}const Xr=cn(Yr,!0),Zn=Xr[0],Qn=Xr[1],ar=(s,e,r)=>r>32?un(s,e,r):ln(s,e,r),cr=(s,e,r)=>r>32?hn(s,e,r):dn(s,e,r);function ei(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],p=ar(l,u,1)^r[a],g=cr(l,u,1)^r[a+1];for(let _=0;_<50;_+=10)s[o+_]^=p,s[o+_+1]^=g}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=jr[o],c=ar(n,i,a),l=cr(n,i,a),u=zr[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Zn[t],s[1]^=Qn[t]}Me(r)}class Dt{constructor(e,r,t,n=!1,i=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,me(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Js(this.state)}clone(){return this._cloneInto()}keccak(){Yt(this.state32),ei(this.state32,this.rounds),Yt(this.state32),this.posOut=0,this.pos=0}update(e){Be(this),X(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Be(this,!1),X(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return me(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(vr(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Me(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Dt(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const ti=(s,e,r,t={})=>Er(()=>new Dt(e,s,r),t),lr=ti(1,136,32),ri=60;class si{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=at.createRemoteJWKSet(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+ri<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await at.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return at.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
7
|
-
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=lr(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=ni(a),l=c.slice(0,32),u=c.slice(32,64),p=c[64],g=p>=27?p-27:p,y=new Vn.Signature(dr(l),dr(u)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),v=lr(y);return"0x"+Ge(v.slice(12))}}function ni(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function dr(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const ii=3e4,oi=1e3;class ai{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,oi*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??ii);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const ci=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ie{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Ie.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Ie.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Ie.generateRandom16Hex(),l=Ie.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),L(),t(new Error("Authentication timeout"))},5*60*1e3),x=10,y=30;let v=0,A=null;const R=()=>{clearInterval(k),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+y+"초간 대기합니다"),A=setTimeout(()=>{L(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},y*1e3)},k=setInterval(()=>{v++;try{if(!g.closed)return;const V=typeof document<"u"&&document.hasFocus();v<=x&&!V?R():(L(),t(new Error("로그인이 취소되었습니다")))}catch{R()}},1e3),L=()=>{clearTimeout(_),clearInterval(k),A&&clearTimeout(A),window.removeEventListener("message",D)},D=V=>{if(V.origin!==e.expectedOrigin)return;if(!ci.has(V.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",V.origin),L(),t(new Error("Unauthorized OAuth origin"));return}L();const Q=typeof V.data.status=="string",q=Q?V.data.data??{}:V.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Q?"wrapped":"flat",status:Q?V.data.status:"(flat)"});const J=(q==null?void 0:q.state)??V.data.state;if(!J||J!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Q&&V.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",q==null?void 0:q.error),t(new Error((q==null?void 0:q.error)||"Authentication failed"));return}if(!Q&&(q!=null&&q.error)){d.error("[CROSSx] OAuth 실패:",q.error),t(new Error(q.error||"Authentication failed"));return}const te=q==null?void 0:q.idToken,G=q==null?void 0:q.accessToken,B=G??te,H=(q==null?void 0:q.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!G,hasIdToken:!!te,hasEmail:!!H}),!B){d.error("[CROSSx] 토큰을 찾을 수 없음:",V.data),t(new Error("Token not found in response"));return}const m={token:B,email:H},w=T=>{Ie.verifyIdTokenNonce(T,l).then(()=>r(m)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};G?G.split(".").length===3?w(G):te?w(te):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(m)):te?w(te):t(new Error("Token not found in response"))};window.addEventListener("message",D)})}}const He="crossx_wallet_data",Oe="crossx_mock_pin_hash";class li{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(He)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(He);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(He,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Oe,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new f(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(He);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Oe);return r&&r!==e?!1:(r||await this.storage.set(Oe,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new f(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Oe);if(n&&t&&n!==t)throw new f(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Oe,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new f(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new f(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(He,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Oe,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Te{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Vt))return e;const r=!e||this.tokenStore.isExpiringSoon(Vt);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const x=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:x,url:o,method:e});const y=Te.mapGatewayError(_.code,_.data);if(y===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(y===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new f(h.USER_NOT_FOUND,Te.getGatewayErrorMessage(_.code,x));const v=y===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:y,A=v===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Te.getGatewayErrorMessage(_.code,x),R=_.data;let k;throw y===h.PIN_LOCKED?k=Te.extractLockDetails(R):y===h.ADDRESS_LIMIT_EXCEEDED?k={limit:Xe,raw:R}:k=R??void 0,new f(v,A,k)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(g){if(g instanceof f)throw g;const _=((l=g.response)==null?void 0:l.status)??g.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=g.response)!=null&&u.data){const x=g.response.data,y=x.message||x.data||"API 요청에 실패했습니다",v=x.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:v,message:y,url:o,method:e,status:(p=g.response)==null?void 0:p.status}),new f(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${v}): ${y}`)}throw g}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new f(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new f(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new f(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new f(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new f(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new f(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new f(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new f(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return Te.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${Xe} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class di{constructor(e,r,t){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(n,i)=>e.prepare(n,i)),e.migrateWallet&&(this.migrateWallet=(n,i)=>e.migrateWallet(n,i)),e.verifyPin&&(this.verifyPin=n=>e.verifyPin(n)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(n,i)=>e.verifyRecoveryPin(n,i))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){const c=await a.signMessage({chainId:r,message:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class We{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=We.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?ks:Ts;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new f(We.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=We.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new f(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(st).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const ur="__crossx-confirm-style",ee="__crossx-confirm-overlay",ui={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function hr(s,e){const r=ui[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const hi=`
|
|
8
|
-
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
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"},xs={ko:fs,en:wr};function xe(s="en",e){return xs[s]??wr}function gs(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Ft="crossx_access_token",Ut="crossx_refresh_token",Ht="crossx_user_info",rt=class rt{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${u}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new f(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=gs(this.getLocale()),c=`${o}${i}`,l=c.includes("?")?"&":"?",u=`${c}${l}locale=${a}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const p=await this.oauth.openAuth({authUrl:u,expectedOrigin:new URL(o).origin});r=p.token,t=p.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new f(h.OAUTH_POPUP_BLOCKED,i):new f(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const p=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=p.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new f(h.AUTH_FAILED,"Access token 검증 실패");const p=u.payload;r={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new f(h.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:x}=await this.exchangeFirebaseToken(e,u);let _,g,w;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),g=(i=A.firebase)==null?void 0:i.sign_in_provider;const T=((o=A.firebase)==null?void 0:o.identities)??{};w=A.email??((a=T.email)==null?void 0:a[0]),g==="google.com"?_=(c=T["google.com"])==null?void 0:c[0]:g==="apple.com"&&(_=(l=T["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",g,"hasProviderSub:",!!_,"email:",w??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const A=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const T=await this.crypto.verifyJWT(p);if(n=T.signatureVerified??!1,!T.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const C=T.payload,L=C.email??w??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",C.email??"(없음)","/ Firebase JWT:",w??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:C.sub,email:L,signInProvider:g,providerSub:_},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??r,signInProvider:g,providerSub:_},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const b=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,b),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new f(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new f(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new f(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof f&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=rt.REFRESH_RELOGIN_CODES.has(c.code);throw new f(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new f(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof f&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof f&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Ht);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(Ft);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Ut);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Ht),await this.storage.remove(Ft),await this.storage.remove(Ut),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof f&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof f&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};rt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let mt=rt;class ws{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class ms{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new f(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class It{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class ys{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new f(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class bs{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function vs(){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 _e{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await _e.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=_e.getBridge(),!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new f(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=vs(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new f(h.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new f(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof f)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new f(h.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new f(h.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof f?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new f(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new f(h.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new f(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof f?r:(d.warn("[RNBridge] Session restore Firebase token request failed",r),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new f(h.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}const De={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 Ss(s){const e=s.environment;return e&&e in De?De[e]:null}function mr(){try{if(typeof __CROSSX_CONFIG__<"u"){const s=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Ss(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in De)return De[s]}catch{}return De.production}const Es=2e3,Wt=6e4,As=1e3,Is=1e4,ks="0x77359400",Gt="0x3B9ACA00",qt=130,kt=6,Kt=18,Vt=3e4,Ts=5*60*1e3,Rs=30*1e3,Xe=100,Cs="crossx-sdk-js/2.2.4";function yr(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Ns(s,e=kt){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Kt),n=r/t,o=(r%t).toString().padStart(Kt,"0"),a=yr(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function qe(s,e,r,t=kt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=yr(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Ps(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==qt)throw new f(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${qt} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Os(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new f(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Ls(s,e){const r=Ds(e);if(s==="0"){if(r!==void 0&&r!==0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new f(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Ds(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Oe{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new f(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=xe(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof f){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Oe.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof f&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=xe(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.session_alert_title,message:l.alert_session_expired,email:u?this.deps.maskEmail(u,l.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=xe(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof f){if(t=Oe.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof f&&(t=Oe.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===h.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Oe.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Bs{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new f(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function $s(s){return s==="google"||s==="apple"}class Ms{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=$s(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=xe(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=xe(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof f&&r.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof f&&r.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof f)||r.code!==h.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new f(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new f(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Fs{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const p=o.find(x=>x.address.toLowerCase()===r.toLowerCase());p?c=p:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(p=>p.index===e)??o[0]:c=o[0];l?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const u=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,u?{walletName:t}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Us{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!p){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(p.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const x=p.pinStatus;if(o=x.maxAttempts,i=o-x.remainingAttempts,x.remainingAttempts===0&&x.lockExpiresAt){const _=x.lockExpiresAt*1e3,g=Math.max(1,Math.round((_-Date.now())/1e3)),w=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${g}초, 메시지: ${w}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(g,w),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof f))throw p;if(p.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const x=xe(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:x.session_alert_title,message:x.alert_session_expired,email:_?this.deps.maskEmail(_,x.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const x=p.details;if(o=(x==null?void 0:x.maxAttempts)??5,(x==null?void 0:x.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((x==null?void 0:x.lockExpiresAt)??0)*1e3,g=Math.max(1,Math.round((_-Date.now())/1e3)),w=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${g}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(g,w),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof f&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof f&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=xe(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:x?this.deps.maskEmail(x,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const w=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",w.address),w}catch(w){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",w),w}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Hs{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,x]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const _=x;if(_){const g=Gt;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(g)).toString(16)}`,c.maxPriorityFeePerGas=g,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=ks,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Gt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ws{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new f(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof f)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Gs(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class qs{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Gs((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Ks{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new f(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Vs{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new f(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new f(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class zs{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",o);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(o);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof f&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new f(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function zt(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class js{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new f(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new f(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=zt(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof f?c:new f(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(zt(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new f(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof f?i:new f(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof f&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:h.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:h.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:h.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new f(n.code,n.message)}}function lt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Re=class Re extends bs{constructor(e,r,t,n,i,o,a,c,l,u,p){var x,_;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._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&&Mt(e.logger),this.confirmation=l,this.pinStore=p??new It,this.stateManager=new qs({setState:g=>{g.authenticated!==void 0&&(this.authenticated=g.authenticated),g.userId!==void 0&&(this.userId=g.userId),g.address!==void 0&&(this.address=g.address),g.activeWalletIndex!==void 0&&(this.activeWalletIndex=g.activeWalletIndex),g.userEmail!==void 0&&(this.userEmail=g.userEmail),g.providerSub!==void 0&&(this.providerSub=g.providerSub),g.loginType!==void 0&&(this.loginType=g.loginType),g.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=g.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:g,index:w,walletName:b})=>{const A={address:g,index:w};b!==void 0&&(A.walletName=b),this.emit("addressChanged",A)},emitAuthChanged:({isAuthenticated:g,address:w,userId:b})=>{this.emit("authChanged",{isAuthenticated:g,address:w,userId:b})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Re.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Oe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:lt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Bs({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Fs({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(g,w,b)=>this.setActiveWallet(g,w,b)}),this.migrationOrchestrator=new Us({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(g,w)=>this.migrateWalletUseCase.execute(g,w),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:lt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var g;return((g=this._config.migration)==null?void 0:g.allowSkip)??!0}}),this.transactionLifecycleService=new Hs({getActiveAddress:()=>this.address,estimateGas:(g,w)=>this.estimateGas(g,w),getBaseFeePerGas:g=>this.getBaseFeePerGas(g),jsonRpcCall:(g,w,b)=>this.jsonRpc.call(g,w,b)}),this.signatureVerifier=new Ws(this.crypto),this.addressResolverService=new Ks({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Vs({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new zs({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(g,w)=>this.setActiveWallet(g,w),showWalletCreated:()=>{var g,w;return((w=(g=this.confirmation).showWalletCreatedPrompt)==null?void 0:w.call(g))??Promise.resolve()}}),this.tokenHistoryService=new js({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Ms({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:g=>{this._isRecoveringSession=g},setAuthenticated:g=>{this.authenticated=g},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:g=>this.signInUseCase.execute(g),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:g=>this.confirmation.showSessionAlert(g),clearAuthState:()=>this.clearAuthState(),applyAuthResult:g=>this.applyAuthResult(g),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:lt}),this.chainRegistry=u,this.jsonRpc=new ys(u,i),this.signInUseCase=new mt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new ws(this.internalConfig,t,c),this.migrateWalletUseCase=new ms(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.2.4 초기화 중..."),this.confirmation.setMessages(xe(this._config.locale));try{const n=mr();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Re.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),u=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,u?{walletName:u}:void 0);else try{await this.loadWalletAfterAuth(o,a,u)}catch(p){if(!(p instanceof f&&p.code===h.PIN_CANCELLED))throw p;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v2.2.4 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new f(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!_e.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new _e({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.2.4",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof f&&r.code===h.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(d.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new f(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new f(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return _e.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(t!=null&&t.success)return t}let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:us(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new f(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof f&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r))}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",t)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof f&&t.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new f(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof f?t:new f(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=_e.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new f(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof f&&t.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof f&&t.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof f?r:new f(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof f?e:new f(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof f?r:new f(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(xe(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new f(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Ls(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Ps(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof f?i:new f(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(Re.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return Os(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return p.txHash??p.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Cs).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof f)throw o;const a=o instanceof Error?o.message:String(o);throw new f(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??As,i=Is,o=t.timeoutMs??Wt,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new f(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var w,b;if(this._isAuthenticatedViaRNBridge){const A=_e.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??Es,l=i??((b=this._config.receiptPolling)==null?void 0:b.timeoutMs)??Wt,u=ct(e),p=r.from??"";let x,_;const g=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{x=A;const T=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),C=r.value?BigInt(r.value):0n,L=qe(r.value,u.symbol,u.decimals,this._config.displayDecimals),U=qe("0x"+T.toString(16),u.symbol,u.decimals,this._config.displayDecimals),H=qe("0x"+(C+T).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:L,fees:U,total:H,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(_=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:p,to:r.to,amount:qe(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},g),_)throw _;return{chainId:e,txHash:a,receipt:x}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new f(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof f?n:new f(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new f(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new f(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Ns(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new gr(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof f)throw n;const i=n instanceof Error?n.message:String(n);throw new f(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=_e.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated){d.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Mt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Re.WALLET_PREF_KEY="wallet_preference",Re.OFFCHAIN_CHAIN_ID="0";let Je=Re;class Ys{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const dt="crossx-sdk",Xs=1,de="data",Ae="keys",Ke="aes-primary",Js=12;class jt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,Xs);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(de)||i.createObjectStore(de),i.objectStoreNames.contains(Ae)||i.createObjectStore(Ae)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ae,Ke);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(Ae,Ke,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===dt)return null;try{const e=await this.openDB(dt),r=e.transaction([Ae,de],"readonly"),t=r.objectStore(Ae).get(Ke),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(de).getAll(),o=r.objectStore(de).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ae,Ke,n);for(let l=0;l<c.length;l++)await this.idbPut(de,String(c[l]),a[l]);return indexedDB.deleteDatabase(dt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Js);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(de,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(de,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(de,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(de)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Tt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function we(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function X(s,e,r=""){const t=Tt(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function br(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(s.outputLen),we(s.blockLen)}function $e(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function vr(s,e){X(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Zs(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Me(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function ut(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ue(s,e){return s<<32-e|s>>>e}const Qs=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function en(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function tn(s){for(let e=0;e<s.length;e++)s[e]=en(s[e]);return s}const Yt=Qs?s=>s:tn,Sr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",rn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ge(s){if(X(s),Sr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=rn[s[r]];return e}const he={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xt(s){if(s>=he._0&&s<=he._9)return s-he._0;if(s>=he.A&&s<=he.F)return s-(he.A-10);if(s>=he.a&&s<=he.f)return s-(he.a-10)}function Ze(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Sr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=Xt(s.charCodeAt(i)),a=Xt(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Se(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];X(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function Er(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Ar(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const sn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function nn(s,e,r){return s&e^~s&r}function on(s,e,r){return s&e^s&r^e&r}class an{constructor(e,r,t,n){O(this,"blockLen");O(this,"outputLen");O(this,"padOffset");O(this,"isLE");O(this,"buffer");O(this,"view");O(this,"finished",!1);O(this,"length",0);O(this,"pos",0);O(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ut(this.buffer)}update(e){$e(this),X(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=ut(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$e(this),vr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Me(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)r[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=ut(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ve=BigInt(2**32-1),Jt=BigInt(32);function cn(s,e=!1){return e?{h:Number(s&Ve),l:Number(s>>Jt&Ve)}:{h:Number(s>>Jt&Ve)|0,l:Number(s&Ve)|0}}function ln(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=cn(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const dn=(s,e,r)=>s<<r|e>>>32-r,un=(s,e,r)=>e<<r|s>>>32-r,hn=(s,e,r)=>e<<r-32|s>>>64-r,pn=(s,e,r)=>s<<r-32|e>>>64-r,_n=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),be=new Uint32Array(64);class fn extends an{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let p=0;p<16;p++,r+=4)be[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const x=be[p-15],_=be[p-2],g=ue(x,7)^ue(x,18)^x>>>3,w=ue(_,17)^ue(_,19)^_>>>10;be[p]=w+be[p-7]+g+be[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const x=ue(a,6)^ue(a,11)^ue(a,25),_=u+x+nn(a,c,l)+_n[p]+be[p]|0,w=(ue(t,2)^ue(t,13)^ue(t,22))+on(t,n,i)|0;u=l,l=c,c=a,a=o+_|0,o=i,i=n,n=t,t=_+w|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){Me(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Me(this.buffer)}}class xn extends fn{constructor(){super(32);O(this,"A",ye[0]|0);O(this,"B",ye[1]|0);O(this,"C",ye[2]|0);O(this,"D",ye[3]|0);O(this,"E",ye[4]|0);O(this,"F",ye[5]|0);O(this,"G",ye[6]|0);O(this,"H",ye[7]|0)}}const gn=Er(()=>new xn,sn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Rt=BigInt(0),yt=BigInt(1);function Qe(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Ir(s){if(typeof s=="bigint"){if(!Ye(s))throw new Error("positive bigint expected, got "+s)}else we(s);return s}function ze(s){const e=Ir(s).toString(16);return e.length&1?"0"+e:e}function kr(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Rt:BigInt("0x"+s)}function nt(s){return kr(Ge(s))}function Tr(s){return kr(Ge(wn(X(s)).reverse()))}function Ct(s,e){we(e),s=Ir(s);const r=Ze(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Rr(s,e){return Ct(s,e).reverse()}function wn(s){return Uint8Array.from(s)}const Ye=s=>typeof s=="bigint"&&Rt<=s;function mn(s,e,r){return Ye(s)&&Ye(e)&&Ye(r)&&e<=s&&s<r}function yn(s,e,r,t){if(!mn(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function bn(s){let e;for(e=0;s>Rt;s>>=yt,e+=1);return e}const Nt=s=>(yt<<BigInt(s))-yt;function vn(s,e,r){if(we(s,"hashLen"),we(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=b=>new Uint8Array(b),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},x=(...b)=>r(l,Se(c,...b)),_=(b=n)=>{l=x(i,b),c=x(),b.length!==0&&(l=x(o,b),c=x())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0;const A=[];for(;b<e;){c=x();const T=c.slice();A.push(T),b+=c.length}return Se(...A)};return(b,A)=>{p(),_(b);let T;for(;!(T=A(g()));)_();return p(),T}}function Pt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function Zt(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),re=BigInt(1),Ce=BigInt(2),Cr=BigInt(3),Nr=BigInt(4),Pr=BigInt(5),Sn=BigInt(7),Or=BigInt(8),En=BigInt(9),Lr=BigInt(16);function le(s,e){const r=s%e;return r>=se?r:e+r}function oe(s,e,r){let t=s;for(;e-- >se;)t*=t,t%=r;return t}function Qt(s,e){if(s===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let r=le(s,e),t=e,n=se,i=re;for(;r!==se;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==re)throw new Error("invert: does not exist");return le(n,e)}function Ot(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Dr(s,e){const r=(s.ORDER+re)/Nr,t=s.pow(e,r);return Ot(s,t,e),t}function An(s,e){const r=(s.ORDER-Pr)/Or,t=s.mul(e,Ce),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Ce),n),a=s.mul(i,s.sub(o,s.ONE));return Ot(s,a,e),a}function In(s){const e=it(s),r=Br(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+Sn)/Lr;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),x=a.mul(l,i),_=a.eql(a.sqr(u),c),g=a.eql(a.sqr(p),c);l=a.cmov(l,u,_),u=a.cmov(x,p,g);const w=a.eql(a.sqr(u),c),b=a.cmov(l,u,w);return Ot(a,b,c),b}}function Br(s){if(s<Cr)throw new Error("sqrt is not defined for small field");let e=s-re,r=0;for(;e%Ce===se;)e/=Ce,r++;let t=Ce;const n=it(s);for(;er(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Dr;let i=n.pow(t,e);const o=(e+re)/Ce;return function(c,l){if(c.is0(l))return l;if(er(c,l)!==1)throw new Error("Cannot find square root");let u=r,p=c.mul(c.ONE,i),x=c.pow(l,e),_=c.pow(l,o);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let g=1,w=c.sqr(x);for(;!c.eql(w,c.ONE);)if(g++,w=c.sqr(w),g===u)throw new Error("Cannot find square root");const b=re<<BigInt(u-g-1),A=c.pow(p,b);u=g,p=c.sqr(A),x=c.mul(x,p),_=c.mul(_,A)}return _}}function kn(s){return s%Nr===Cr?Dr:s%Or===Pr?An:s%Lr===En?In(s):Br(s)}const Tn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Rn(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Tn.reduce((t,n)=>(t[n]="function",t),e);return Pt(s,r),s}function Cn(s,e,r){if(r<se)throw new Error("invalid exponent, negatives unsupported");if(r===se)return s.ONE;if(r===re)return e;let t=s.ONE,n=e;for(;r>se;)r&re&&(t=s.mul(t,n)),n=s.sqr(n),r>>=re;return t}function $r(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function er(s,e){const r=(s.ORDER-re)/Ce,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Nn(s,e){e!==void 0&&we(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Pn{constructor(e,r={}){O(this,"ORDER");O(this,"BITS");O(this,"BYTES");O(this,"isLE");O(this,"ZERO",se);O(this,"ONE",re);O(this,"_lengths");O(this,"_sqrt");O(this,"_mod");var o;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Nn(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return le(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return le(e*e,this.ORDER)}add(e,r){return le(e+r,this.ORDER)}sub(e,r){return le(e-r,this.ORDER)}mul(e,r){return le(e*r,this.ORDER)}pow(e,r){return Cn(this,e,r)}div(e,r){return le(e*Qt(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Qt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=kn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Rr(e,this.BYTES):Ct(e,this.BYTES)}fromBytes(e,r=!1){X(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Tr(e):nt(e);if(a&&(c=le(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return $r(this,e)}cmov(e,r,t){return t?r:e}}function it(s,e={}){return new Pn(s,e)}function Mr(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Fr(s){const e=Mr(s);return e+Math.ceil(e/2)}function On(s,e,r=!1){X(s);const t=s.length,n=Mr(e),i=Fr(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?Tr(s):nt(s),a=le(o,e-re)+re;return r?Rr(a,n):Ct(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Fe=BigInt(0),Ne=BigInt(1);function et(s,e){const r=e.negate();return s?r:e}function tr(s,e){const r=$r(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Ur(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function ht(s,e){Ur(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Nt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function rr(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=Ne);const l=e*t,u=l+Math.abs(a)-1,p=a===0,x=a<0,_=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:x,isNegF:_,offsetF:l}}const pt=new WeakMap,Hr=new WeakMap;function _t(s){return Hr.get(s)||1}function sr(s){if(s!==Fe)throw new Error("invalid wNAF")}class Ln{constructor(e,r){O(this,"BASE");O(this,"ZERO");O(this,"Fn");O(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Fe;)r&Ne&&(t=t.add(n)),n=n.double(),r>>=Ne;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=ht(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=ht(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:x,offsetF:_}=rr(t,a,o);t=c,u?i=i.add(et(x,r[_])):n=n.add(et(p,r[l]))}return sr(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=ht(e,this.bits);for(let o=0;o<i.windows&&t!==Fe;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=rr(t,o,i);if(t=a,!l){const p=r[c];n=n.add(u?p.negate():p)}}return sr(t),n}getPrecomputes(e,r,t){let n=pt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),pt.set(r,n))),n}cached(e,r,t){const n=_t(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=_t(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Ur(r,this.bits),Hr.set(e,r),pt.delete(e)}hasCache(e){return _t(e)!==1}}function Dn(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Fe||t>Fe;)r&Ne&&(i=i.add(n)),t&Ne&&(o=o.add(n)),n=n.double(),r>>=Ne,t>>=Ne;return{p1:i,p2:o}}function nr(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Rn(e),e}else return it(s,{isLE:r})}function Bn(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Fe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=nr(e.p,r.Fp,t),i=nr(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function $n(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Wr{constructor(e,r){O(this,"oHash");O(this,"iHash");O(this,"blockLen");O(this,"outputLen");O(this,"finished",!1);O(this,"destroyed",!1);if(br(e),X(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Me(n)}update(e){return $e(this),this.iHash.update(e),this}digestInto(e){$e(this),X(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Gr=(s,e,r)=>new Wr(s,e).update(r).digest();Gr.create=(s,e)=>new Wr(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ir=(s,e)=>(s+(s>=0?e:-e)/qr)/e;function Mn(s,e,r){const[[t,n],[i,o]]=e,a=ir(o*s,r),c=ir(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const p=l<fe,x=u<fe;p&&(l=-l),x&&(u=-u);const _=Nt(Math.ceil(bn(r)/2))+Be;if(l<fe||l>=_||u<fe||u>=_)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:x,k2:u}}function bt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function ft(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return Qe(r.lowS,"lowS"),Qe(r.prehash,"prehash"),r.format!==void 0&&bt(r.format),r}class Fn extends Error{constructor(e=""){super(e)}}const ve={Err:Fn,_tlv:{encode:(s,e)=>{const{Err:r}=ve;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=ze(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?ze(n.length/2|128):"";return ze(s)+i+n+e},decode(s,e){const{Err:r}=ve;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=ve;if(s<fe)throw new e("integer: negative integers are not allowed");let r=ze(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=ve;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return nt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=ve,n=X(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=ve,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},fe=BigInt(0),Be=BigInt(1),qr=BigInt(2),je=BigInt(3),Un=BigInt(4);function Hn(s,e={}){const r=Bn("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Pt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Vr(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(W,y,m){const{x:k,y:N}=y.toAffine(),M=t.toBytes(k);if(Qe(m,"isCompressed"),m){u();const D=!t.isOdd(N);return Se(Kr(D),M)}else return Se(Uint8Array.of(4),M,t.toBytes(N))}function x(W){X(W,void 0,"Point");const{publicKey:y,publicKeyUncompressed:m}=l,k=W.length,N=W[0],M=W.subarray(1);if(k===y&&(N===2||N===3)){const D=t.fromBytes(M);if(!t.isValid(D))throw new Error("bad point: is not on curve, wrong x");const $=w(D);let P;try{P=t.sqrt($)}catch(E){const R=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+R)}u();const G=t.isOdd(P);return(N&1)===1!==G&&(P=t.neg(P)),{x:D,y:P}}else if(k===m&&N===4){const D=t.BYTES,$=t.fromBytes(M.subarray(0,D)),P=t.fromBytes(M.subarray(D,D*2));if(!b($,P))throw new Error("bad point: is not on curve");return{x:$,y:P}}else throw new Error(`bad point: got length ${k}, expected compressed=${y} or uncompressed=${m}`)}const _=e.toBytes||p,g=e.fromBytes||x;function w(W){const y=t.sqr(W),m=t.mul(y,W);return t.add(t.add(m,t.mul(W,i.a)),i.b)}function b(W,y){const m=t.sqr(y),k=w(W);return t.eql(m,k)}if(!b(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,je),Un),T=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,T)))throw new Error("bad curve params: a or b");function C(W,y,m=!1){if(!t.isValid(y)||m&&t.is0(y))throw new Error(`bad point coordinate ${W}`);return y}function L(W){if(!(W instanceof J))throw new Error("Weierstrass Point expected")}function U(W){if(!c||!c.basises)throw new Error("no endo");return Mn(W,c.basises,n.ORDER)}const H=Zt((W,y)=>{const{X:m,Y:k,Z:N}=W;if(t.eql(N,t.ONE))return{x:m,y:k};const M=W.is0();y==null&&(y=M?t.ONE:t.inv(N));const D=t.mul(m,y),$=t.mul(k,y),P=t.mul(N,y);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:D,y:$}}),ee=Zt(W=>{if(W.is0()){if(e.allowInfinityPoint&&!t.is0(W.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:m}=W.toAffine();if(!t.isValid(y)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!b(y,m))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function K(W,y,m,k,N){return m=new J(t.mul(m.X,W),m.Y,m.Z),y=et(k,y),m=et(N,m),y.add(m)}const B=class B{constructor(y,m,k){O(this,"X");O(this,"Y");O(this,"Z");this.X=C("x",y),this.Y=C("y",m,!0),this.Z=C("z",k),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){const{x:m,y:k}=y||{};if(!y||!t.isValid(m)||!t.isValid(k))throw new Error("invalid affine point");if(y instanceof B)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(k)?B.ZERO:new B(m,k,t.ONE)}static fromBytes(y){const m=B.fromAffine(g(X(y,void 0,"point")));return m.assertValidity(),m}static fromHex(y){return B.fromBytes(Ze(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,m=!0){return q.createCache(this,y),m||this.multiply(je),this}assertValidity(){ee(this)}hasEvenY(){const{y}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(y)}equals(y){L(y);const{X:m,Y:k,Z:N}=this,{X:M,Y:D,Z:$}=y,P=t.eql(t.mul(m,$),t.mul(M,N)),G=t.eql(t.mul(k,$),t.mul(D,N));return P&&G}negate(){return new B(this.X,t.neg(this.Y),this.Z)}double(){const{a:y,b:m}=i,k=t.mul(m,je),{X:N,Y:M,Z:D}=this;let $=t.ZERO,P=t.ZERO,G=t.ZERO,v=t.mul(N,N),E=t.mul(M,M),R=t.mul(D,D),I=t.mul(N,M);return I=t.add(I,I),G=t.mul(N,D),G=t.add(G,G),$=t.mul(y,G),P=t.mul(k,R),P=t.add($,P),$=t.sub(E,P),P=t.add(E,P),P=t.mul($,P),$=t.mul(I,$),G=t.mul(k,G),R=t.mul(y,R),I=t.sub(v,R),I=t.mul(y,I),I=t.add(I,G),G=t.add(v,v),v=t.add(G,v),v=t.add(v,R),v=t.mul(v,I),P=t.add(P,v),R=t.mul(M,D),R=t.add(R,R),v=t.mul(R,I),$=t.sub($,v),G=t.mul(R,E),G=t.add(G,G),G=t.add(G,G),new B($,P,G)}add(y){L(y);const{X:m,Y:k,Z:N}=this,{X:M,Y:D,Z:$}=y;let P=t.ZERO,G=t.ZERO,v=t.ZERO;const E=i.a,R=t.mul(i.b,je);let I=t.mul(m,M),F=t.mul(k,D),V=t.mul(N,$),j=t.add(m,k),z=t.add(M,D);j=t.mul(j,z),z=t.add(I,F),j=t.sub(j,z),z=t.add(m,N);let Y=t.add(M,$);return z=t.mul(z,Y),Y=t.add(I,V),z=t.sub(z,Y),Y=t.add(k,N),P=t.add(D,$),Y=t.mul(Y,P),P=t.add(F,V),Y=t.sub(Y,P),v=t.mul(E,z),P=t.mul(R,V),v=t.add(P,v),P=t.sub(F,v),v=t.add(F,v),G=t.mul(P,v),F=t.add(I,I),F=t.add(F,I),V=t.mul(E,V),z=t.mul(R,z),F=t.add(F,V),V=t.sub(I,V),V=t.mul(E,V),z=t.add(z,V),I=t.mul(F,z),G=t.add(G,I),I=t.mul(Y,z),P=t.mul(j,P),P=t.sub(P,I),I=t.mul(j,F),v=t.mul(Y,v),v=t.add(v,I),new B(P,G,v)}subtract(y){return this.add(y.negate())}is0(){return this.equals(B.ZERO)}multiply(y){const{endo:m}=e;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let k,N;const M=D=>q.cached(this,D,$=>tr(B,$));if(m){const{k1neg:D,k1:$,k2neg:P,k2:G}=U(y),{p:v,f:E}=M($),{p:R,f:I}=M(G);N=E.add(I),k=K(m.beta,v,R,D,P)}else{const{p:D,f:$}=M(y);k=D,N=$}return tr(B,[k,N])[0]}multiplyUnsafe(y){const{endo:m}=e,k=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===fe||k.is0())return B.ZERO;if(y===Be)return k;if(q.hasCache(this))return this.multiply(y);if(m){const{k1neg:N,k1:M,k2neg:D,k2:$}=U(y),{p1:P,p2:G}=Dn(B,k,M,$);return K(m.beta,P,G,N,D)}else return q.unsafe(k,y)}toAffine(y){return H(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Be?!0:y?y(B,this):q.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Be?this:y?y(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return Qe(y,"isCompressed"),this.assertValidity(),_(B,this,y)}toHex(y=!0){return Ge(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};O(B,"BASE",new B(i.Gx,i.Gy,t.ONE)),O(B,"ZERO",new B(t.ZERO,t.ONE,t.ZERO)),O(B,"Fp",t),O(B,"Fn",n);let J=B;const te=n.BITS,q=new Ln(J,e.endo?Math.ceil(te/2):te);return J.BASE.precompute(8),J}function Kr(s){return Uint8Array.of(s?2:3)}function Vr(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wn(s,e={}){const{Fn:r}=s,t=e.randomBytes||Ar,n=Object.assign(Vr(s.Fp,r),{seed:Fr(r.ORDER)});function i(_){try{const g=r.fromBytes(_);return r.isValidNot0(g)}catch{return!1}}function o(_,g){const{publicKey:w,publicKeyUncompressed:b}=n;try{const A=_.length;return g===!0&&A!==w||g===!1&&A!==b?!1:!!s.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return On(X(_,n.seed,"seed"),r.ORDER)}function c(_,g=!0){return s.BASE.multiply(r.fromBytes(_)).toBytes(g)}function l(_){const{secretKey:g,publicKey:w,publicKeyUncompressed:b}=n;if(!Tt(_)||"_lengths"in r&&r._lengths||g===w)return;const A=X(_,void 0,"key").length;return A===w||A===b}function u(_,g,w=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");const b=r.fromBytes(_);return s.fromBytes(g).multiply(b).toBytes(w)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=$n(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,Point:s,utils:p,lengths:n})}function Gn(s,e,r={}){br(e),Pt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Ar,n=r.hmac||((y,m)=>Gr(e,y,m)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:x,lengths:_}=Wn(s,r),g={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*qr<i.ORDER;function b(y){const m=a>>Be;return y>m}function A(y,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return m}function T(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function C(y,m){bt(m);const k=_.signature,N=m==="compact"?k:m==="recovered"?k+1:void 0;return X(y,N)}class L{constructor(m,k,N){O(this,"r");O(this,"s");O(this,"recovery");if(this.r=A("r",m),this.s=A("s",k),N!=null){if(T(),![0,1,2,3].includes(N))throw new Error("invalid recovery id");this.recovery=N}Object.freeze(this)}static fromBytes(m,k=g.format){C(m,k);let N;if(k==="der"){const{r:P,s:G}=ve.toSig(X(m));return new L(P,G)}k==="recovered"&&(N=m[0],k="compact",m=m.subarray(1));const M=_.signature/2,D=m.subarray(0,M),$=m.subarray(M,M*2);return new L(o.fromBytes(D),o.fromBytes($),N)}static fromHex(m,k){return this.fromBytes(Ze(m),k)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new L(this.r,this.s,m)}recoverPublicKey(m){const{r:k,s:N}=this,M=this.assertRecovery(),D=M===2||M===3?k+a:k;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const $=i.toBytes(D),P=s.fromBytes(Se(Kr((M&1)===0),$)),G=o.inv(D),v=H(X(m,void 0,"msgHash")),E=o.create(-v*G),R=o.create(N*G),I=s.BASE.multiplyUnsafe(E).add(P.multiplyUnsafe(R));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return b(this.s)}toBytes(m=g.format){if(bt(m),m==="der")return Ze(ve.hexFromSig(this));const{r:k,s:N}=this,M=o.toBytes(k),D=o.toBytes(N);return m==="recovered"?(T(),Se(Uint8Array.of(this.assertRecovery()),M,D)):Se(M,D)}toHex(m){return Ge(this.toBytes(m))}}const U=r.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const k=nt(m),N=m.length*8-c;return N>0?k>>BigInt(N):k},H=r.bits2int_modN||function(m){return o.create(U(m))},ee=Nt(c);function K(y){return yn("num < 2^"+c,y,fe,ee),o.toBytes(y)}function J(y,m){return X(y,void 0,"message"),m?X(e(y),void 0,"prehashed message"):y}function te(y,m,k){const{lowS:N,prehash:M,extraEntropy:D}=ft(k,g);y=J(y,M);const $=H(y),P=o.fromBytes(m);if(!o.isValidNot0(P))throw new Error("invalid private key");const G=[K(P),K($)];if(D!=null&&D!==!1){const I=D===!0?t(_.secretKey):D;G.push(X(I,void 0,"extraEntropy"))}const v=Se(...G),E=$;function R(I){const F=U(I);if(!o.isValidNot0(F))return;const V=o.inv(F),j=s.BASE.multiply(F).toAffine(),z=o.create(j.x);if(z===fe)return;const Y=o.create(V*o.create(E+z*P));if(Y===fe)return;let Ee=(j.x===z?0:2)|Number(j.y&Be),$t=Y;return N&&b(Y)&&($t=o.neg(Y),Ee^=1),new L(z,$t,w?void 0:Ee)}return{seed:v,k2sig:R}}function q(y,m,k={}){const{seed:N,k2sig:M}=te(y,m,k);return vn(e.outputLen,o.BYTES,n)(N,M).toBytes(k.format)}function B(y,m,k,N={}){const{lowS:M,prehash:D,format:$}=ft(N,g);if(k=X(k,void 0,"publicKey"),m=J(m,D),!Tt(y)){const P=y instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}C(y,$);try{const P=L.fromBytes(y,$),G=s.fromBytes(k);if(M&&P.hasHighS())return!1;const{r:v,s:E}=P,R=H(m),I=o.inv(E),F=o.create(R*I),V=o.create(v*I),j=s.BASE.multiplyUnsafe(F).add(G.multiplyUnsafe(V));return j.is0()?!1:o.create(j.x)===v}catch{return!1}}function W(y,m,k={}){const{prehash:N}=ft(k,g);return m=J(m,N),L.fromBytes(y,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:x,lengths:_,Point:s,sign:q,verify:B,recoverPublicKey:W,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Lt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},or=BigInt(2);function Kn(s){const e=Lt.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,p=oe(u,r,e)*u%e,x=oe(p,r,e)*u%e,_=oe(x,or,e)*l%e,g=oe(_,n,e)*_%e,w=oe(g,i,e)*g%e,b=oe(w,a,e)*w%e,A=oe(b,c,e)*b%e,T=oe(A,a,e)*w%e,C=oe(T,r,e)*u%e,L=oe(C,o,e)*g%e,U=oe(L,t,e)*l%e,H=oe(U,or,e);if(!vt.eql(vt.sqr(H),s))throw new Error("Cannot find square root");return H}const vt=it(Lt.p,{sqrt:Kn}),Vn=Hn(Lt,{Fp:vt,endo:qn}),zn=Gn(Vn,gn),jn=BigInt(0),Ue=BigInt(1),Yn=BigInt(2),Xn=BigInt(7),Jn=BigInt(256),Zn=BigInt(113),zr=[],jr=[],Yr=[];for(let s=0,e=Ue,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],zr.push(2*(5*t+r)),jr.push((s+1)*(s+2)/2%64);let n=jn;for(let i=0;i<7;i++)e=(e<<Ue^(e>>Xn)*Zn)%Jn,e&Yn&&(n^=Ue<<(Ue<<BigInt(i))-Ue);Yr.push(n)}const Xr=ln(Yr,!0),Qn=Xr[0],ei=Xr[1],ar=(s,e,r)=>r>32?hn(s,e,r):dn(s,e,r),cr=(s,e,r)=>r>32?pn(s,e,r):un(s,e,r);function ti(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],p=ar(l,u,1)^r[a],x=cr(l,u,1)^r[a+1];for(let _=0;_<50;_+=10)s[o+_]^=p,s[o+_+1]^=x}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=jr[o],c=ar(n,i,a),l=cr(n,i,a),u=zr[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Qn[t],s[1]^=ei[t]}Me(r)}class Dt{constructor(e,r,t,n=!1,i=24){O(this,"state");O(this,"pos",0);O(this,"posOut",0);O(this,"finished",!1);O(this,"state32");O(this,"destroyed",!1);O(this,"blockLen");O(this,"suffix");O(this,"outputLen");O(this,"enableXOF",!1);O(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Zs(this.state)}clone(){return this._cloneInto()}keccak(){Yt(this.state32),ti(this.state32,this.rounds),Yt(this.state32),this.posOut=0,this.pos=0}update(e){$e(this),X(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){$e(this,!1),X(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return we(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(vr(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Me(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Dt(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const ri=(s,e,r,t={})=>Er(()=>new Dt(e,s,r),t),lr=ri(1,136,32),si=60;class ni{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=at.createRemoteJWKSet(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+si<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await at.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return at.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
7
|
+
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=lr(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=ii(a),l=c.slice(0,32),u=c.slice(32,64),p=c[64],x=p>=27?p-27:p,w=new zn.Signature(dr(l),dr(u)).addRecoveryBit(x).recoverPublicKey(o).toBytes(!1).slice(1),b=lr(w);return"0x"+Ge(b.slice(12))}}function ii(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function dr(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const oi=3e4,ai=1e3;class ci{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,ai*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??oi);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const li=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class ke{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=ke.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await ke.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=ke.generateRandom16Hex(),l=ke.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const x=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),L(),t(new Error("Authentication timeout"))},5*60*1e3),g=10,w=30;let b=0,A=null;const T=()=>{clearInterval(C),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+w+"초간 대기합니다"),A=setTimeout(()=>{L(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},w*1e3)},C=setInterval(()=>{b++;try{if(!x.closed)return;const H=typeof document<"u"&&document.hasFocus();b<=g&&!H?T():(L(),t(new Error("로그인이 취소되었습니다")))}catch{T()}},1e3),L=()=>{clearTimeout(_),clearInterval(C),A&&clearTimeout(A),window.removeEventListener("message",U)},U=H=>{if(H.origin!==e.expectedOrigin)return;if(!li.has(H.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",H.origin),L(),t(new Error("Unauthorized OAuth origin"));return}L();const ee=typeof H.data.status=="string",K=ee?H.data.data??{}:H.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:ee?"wrapped":"flat",status:ee?H.data.status:"(flat)"});const J=(K==null?void 0:K.state)??H.data.state;if(!J||J!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ee&&H.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",K==null?void 0:K.error),t(new Error((K==null?void 0:K.error)||"Authentication failed"));return}if(!ee&&(K!=null&&K.error)){d.error("[CROSSx] OAuth 실패:",K.error),t(new Error(K.error||"Authentication failed"));return}const te=K==null?void 0:K.idToken,q=K==null?void 0:K.accessToken,B=q??te,W=(K==null?void 0:K.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!q,hasIdToken:!!te,hasEmail:!!W}),!B){d.error("[CROSSx] 토큰을 찾을 수 없음:",H.data),t(new Error("Token not found in response"));return}const y={token:B,email:W},m=k=>{ke.verifyIdTokenNonce(k,l).then(()=>r(y)).catch(N=>{d.error("[CROSSx] nonce 검증 실패:",N),t(N instanceof Error?N:new Error("nonce verification failed"))})};q?q.split(".").length===3?m(q):te?m(te):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(y)):te?m(te):t(new Error("Token not found in response"))};window.addEventListener("message",U)})}}const He="crossx_wallet_data",Pe="crossx_mock_pin_hash";class di{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(He)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(He);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(He,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Pe,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new f(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(He);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Pe);return r&&r!==e?!1:(r||await this.storage.set(Pe,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new f(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Pe);if(n&&t&&n!==t)throw new f(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Pe,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new f(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new f(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(He,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Pe,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Te{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Vt))return e;const r=!e||this.tokenStore.isExpiringSoon(Vt);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const g=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:g,url:o,method:e});const w=Te.mapGatewayError(_.code,_.data);if(w===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(w===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new f(h.USER_NOT_FOUND,Te.getGatewayErrorMessage(_.code,g));const b=w===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:w,A=b===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Te.getGatewayErrorMessage(_.code,g),T=_.data;let C;throw w===h.PIN_LOCKED?C=Te.extractLockDetails(T):w===h.ADDRESS_LIMIT_EXCEEDED?C={limit:Xe,raw:T}:C=T??void 0,new f(b,A,C)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(x){if(x instanceof f)throw x;const _=((l=x.response)==null?void 0:l.status)??x.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=x.response)!=null&&u.data){const g=x.response.data,w=g.message||g.data||"API 요청에 실패했습니다",b=g.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:b,message:w,url:o,method:e,status:(p=x.response)==null?void 0:p.status}),new f(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${b}): ${w}`)}throw x}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new f(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new f(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new f(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new f(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new f(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new f(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new f(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new f(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return Te.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${Xe} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class ui{constructor(e,r,t,n=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(i,o)=>e.prepare(i,o)),e.migrateWallet&&(this.migrateWallet=(i,o)=>e.migrateWallet(i,o)),e.verifyPin&&(this.verifyPin=i=>e.verifyPin(i)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(i,o)=>e.verifyRecoveryPin(i,o))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();const c=await a.signMessage({chainId:r,message:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){this.assertBridgeSessionActive();const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return this.assertBridgeSessionActive(),{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class We{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=We.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?Rs:Ts;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new f(We.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=We.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new f(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(st).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const ur="__crossx-confirm-style",Q="__crossx-confirm-overlay",hi={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.65)",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.65)",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 hr(s,e){const r=hi[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const pi=`
|
|
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
|
+
#${Q} {
|
|
11
11
|
position: fixed;
|
|
12
12
|
inset: 0;
|
|
13
13
|
z-index: 2147483647;
|
|
@@ -15,7 +15,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
15
15
|
align-items: center;
|
|
16
16
|
justify-content: center;
|
|
17
17
|
background: rgba(0,0,0,0.55);
|
|
18
|
-
font-family: '
|
|
18
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
19
19
|
animation: __crossx-fade-in 0.15s ease;
|
|
20
20
|
pointer-events: auto;
|
|
21
21
|
}
|
|
@@ -26,13 +26,15 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
26
26
|
|
|
27
27
|
.__crossx-card {
|
|
28
28
|
background: var(--cx-bg);
|
|
29
|
-
border:
|
|
29
|
+
border: 1px solid var(--cx-border-medium);
|
|
30
30
|
border-radius: 24px;
|
|
31
31
|
width: 383px;
|
|
32
32
|
max-width: calc(100vw - 32px);
|
|
33
33
|
overflow: hidden;
|
|
34
34
|
position: relative;
|
|
35
35
|
animation: __crossx-slide-up 0.18s ease;
|
|
36
|
+
box-sizing: border-box;
|
|
37
|
+
box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
|
|
36
38
|
}
|
|
37
39
|
@keyframes __crossx-slide-up {
|
|
38
40
|
from { transform: translateY(20px); opacity: 0; }
|
|
@@ -41,35 +43,37 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
41
43
|
|
|
42
44
|
/* ── Header ─────────────────────────────────────────────────────── */
|
|
43
45
|
.__crossx-header {
|
|
44
|
-
padding: 24px
|
|
46
|
+
padding: 24px;
|
|
45
47
|
position: relative;
|
|
46
48
|
}
|
|
47
49
|
.__crossx-title {
|
|
48
|
-
font-size:
|
|
50
|
+
font-size: 20px;
|
|
49
51
|
font-weight: 600;
|
|
50
|
-
line-height: 1.
|
|
52
|
+
line-height: 1.25;
|
|
51
53
|
color: var(--cx-title);
|
|
52
54
|
margin: 0 0 4px 0;
|
|
53
55
|
padding-right: 36px;
|
|
56
|
+
letter-spacing: 0;
|
|
54
57
|
}
|
|
55
58
|
.__crossx-subtitle {
|
|
56
59
|
font-size: 14px;
|
|
57
60
|
font-weight: 400;
|
|
58
|
-
line-height: 1.
|
|
61
|
+
line-height: 1.5;
|
|
59
62
|
color: var(--cx-subtitle);
|
|
60
63
|
margin: 0;
|
|
64
|
+
letter-spacing: -0.01em;
|
|
61
65
|
}
|
|
62
66
|
.__crossx-close {
|
|
63
67
|
position: absolute;
|
|
64
|
-
top:
|
|
65
|
-
right:
|
|
66
|
-
width:
|
|
67
|
-
height:
|
|
68
|
+
top: 24px;
|
|
69
|
+
right: 24px;
|
|
70
|
+
width: 24px;
|
|
71
|
+
height: 24px;
|
|
68
72
|
border: none;
|
|
69
73
|
background: none;
|
|
70
74
|
cursor: pointer;
|
|
71
75
|
color: var(--cx-close);
|
|
72
|
-
border-radius:
|
|
76
|
+
border-radius: 6px;
|
|
73
77
|
display: flex;
|
|
74
78
|
align-items: center;
|
|
75
79
|
justify-content: center;
|
|
@@ -365,7 +369,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
365
369
|
}
|
|
366
370
|
.__crossx-pw-btn {
|
|
367
371
|
width: 100%;
|
|
368
|
-
height:
|
|
372
|
+
height: 48px;
|
|
369
373
|
border: none;
|
|
370
374
|
border-radius: 12px;
|
|
371
375
|
font-size: 16px;
|
|
@@ -375,6 +379,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
375
379
|
transition: background 0.15s, color 0.15s;
|
|
376
380
|
background: var(--cx-input-border);
|
|
377
381
|
color: var(--cx-hint);
|
|
382
|
+
letter-spacing: -0.01em;
|
|
378
383
|
}
|
|
379
384
|
.__crossx-pw-btn:not(:disabled):not(.--disabled) {
|
|
380
385
|
background: var(--cx-primary);
|
|
@@ -385,63 +390,70 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
385
390
|
cursor: not-allowed;
|
|
386
391
|
}
|
|
387
392
|
.__crossx-pw-subtitle {
|
|
388
|
-
font-size:
|
|
393
|
+
font-size: 14px;
|
|
389
394
|
font-weight: 400;
|
|
390
|
-
line-height: 1.
|
|
395
|
+
line-height: 1.5;
|
|
391
396
|
color: var(--cx-subtitle);
|
|
392
397
|
margin: 0;
|
|
398
|
+
letter-spacing: -0.01em;
|
|
393
399
|
}
|
|
394
400
|
|
|
395
401
|
/* ── Password Notice (Consent) Screen ─────────────────────────── */
|
|
396
402
|
.__crossx-pw-notice-header {
|
|
397
403
|
display: flex;
|
|
398
404
|
flex-direction: column;
|
|
399
|
-
gap:
|
|
405
|
+
gap: 6px;
|
|
406
|
+
padding: 12px;
|
|
407
|
+
border: 0.5px solid var(--cx-notice-border);
|
|
408
|
+
border-radius: 12px;
|
|
409
|
+
background: var(--cx-notice-bg);
|
|
400
410
|
}
|
|
401
411
|
.__crossx-pw-notice-title-row {
|
|
402
412
|
display: flex;
|
|
403
413
|
align-items: center;
|
|
404
|
-
gap:
|
|
414
|
+
gap: 6px;
|
|
405
415
|
}
|
|
406
416
|
.__crossx-pw-notice-icon {
|
|
407
417
|
width: 24px;
|
|
408
418
|
height: 24px;
|
|
409
419
|
flex-shrink: 0;
|
|
410
|
-
color: var(--cx-
|
|
420
|
+
color: var(--cx-notice-title);
|
|
411
421
|
}
|
|
412
422
|
.__crossx-pw-notice-title {
|
|
413
|
-
font-size:
|
|
423
|
+
font-size: 18px;
|
|
414
424
|
font-weight: 600;
|
|
415
|
-
line-height: 1.
|
|
416
|
-
color: var(--cx-
|
|
425
|
+
line-height: 1.5;
|
|
426
|
+
color: var(--cx-notice-title);
|
|
417
427
|
margin: 0;
|
|
418
428
|
white-space: nowrap;
|
|
429
|
+
letter-spacing: -0.01em;
|
|
419
430
|
}
|
|
420
431
|
.__crossx-pw-notice-desc {
|
|
421
432
|
font-size: 14px;
|
|
422
433
|
font-weight: 400;
|
|
423
|
-
line-height: 1.
|
|
434
|
+
line-height: 1.5;
|
|
424
435
|
color: var(--cx-value);
|
|
425
436
|
margin: 0;
|
|
437
|
+
letter-spacing: -0.01em;
|
|
426
438
|
}
|
|
427
439
|
.__crossx-pw-notice-checks {
|
|
428
440
|
display: flex;
|
|
429
441
|
flex-direction: column;
|
|
430
|
-
gap:
|
|
442
|
+
gap: 16px;
|
|
431
443
|
}
|
|
432
444
|
.__crossx-pw-notice-item {
|
|
433
445
|
display: flex;
|
|
434
|
-
align-items:
|
|
435
|
-
gap:
|
|
436
|
-
padding:
|
|
437
|
-
border-radius:
|
|
438
|
-
background:
|
|
446
|
+
align-items: flex-start;
|
|
447
|
+
gap: 8px;
|
|
448
|
+
padding: 0;
|
|
449
|
+
border-radius: 0;
|
|
450
|
+
background: transparent;
|
|
439
451
|
cursor: pointer;
|
|
440
452
|
user-select: none;
|
|
441
453
|
transition: background 0.15s;
|
|
442
454
|
}
|
|
443
455
|
.__crossx-pw-notice-item:hover {
|
|
444
|
-
background:
|
|
456
|
+
background: transparent;
|
|
445
457
|
}
|
|
446
458
|
.__crossx-pw-notice-item.--highlight {
|
|
447
459
|
animation: __crossx-notice-pulse 0.5s ease;
|
|
@@ -455,7 +467,9 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
455
467
|
width: 20px;
|
|
456
468
|
height: 20px;
|
|
457
469
|
border-radius: 50%;
|
|
458
|
-
|
|
470
|
+
border: 1px solid var(--cx-border-medium);
|
|
471
|
+
background: transparent;
|
|
472
|
+
color: var(--cx-on-primary);
|
|
459
473
|
display: flex;
|
|
460
474
|
align-items: center;
|
|
461
475
|
justify-content: center;
|
|
@@ -464,6 +478,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
464
478
|
}
|
|
465
479
|
.__crossx-pw-notice-check.--checked {
|
|
466
480
|
background: var(--cx-primary);
|
|
481
|
+
border-color: var(--cx-primary);
|
|
467
482
|
}
|
|
468
483
|
.__crossx-pw-notice-check svg {
|
|
469
484
|
width: 11px;
|
|
@@ -472,15 +487,16 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
472
487
|
.__crossx-pw-notice-item-text {
|
|
473
488
|
font-size: 14px;
|
|
474
489
|
font-weight: 400;
|
|
475
|
-
line-height: 1.
|
|
476
|
-
color: var(--cx-
|
|
490
|
+
line-height: 1.5;
|
|
491
|
+
color: var(--cx-subtitle);
|
|
477
492
|
flex: 1;
|
|
493
|
+
letter-spacing: -0.01em;
|
|
478
494
|
}
|
|
479
495
|
/* Notice screen: button shows primary+opacity even when disabled (interactive guide) */
|
|
480
496
|
.__crossx-pw-body > .__crossx-pw-btn.--disabled {
|
|
481
497
|
background: var(--cx-primary);
|
|
482
498
|
color: var(--cx-on-primary);
|
|
483
|
-
opacity:
|
|
499
|
+
opacity: 1;
|
|
484
500
|
cursor: pointer;
|
|
485
501
|
}
|
|
486
502
|
/* Home indicator bar (mobile only – shown via media query) */
|
|
@@ -1204,6 +1220,99 @@ button.__crossx-connect-other-block:active {
|
|
|
1204
1220
|
width: 100%;
|
|
1205
1221
|
}
|
|
1206
1222
|
/* ── Wallet Selector Modal ─────────────────────────────────── */
|
|
1223
|
+
.__crossx-overlay--wallet-selector {
|
|
1224
|
+
background: rgba(0,0,0,0.7) !important;
|
|
1225
|
+
-webkit-backdrop-filter: blur(3.5px);
|
|
1226
|
+
backdrop-filter: blur(3.5px);
|
|
1227
|
+
}
|
|
1228
|
+
.__crossx-card--wallet-selector {
|
|
1229
|
+
width: 540px;
|
|
1230
|
+
max-width: calc(100vw - 32px);
|
|
1231
|
+
max-height: 90vh;
|
|
1232
|
+
display: flex;
|
|
1233
|
+
flex-direction: column;
|
|
1234
|
+
overflow: hidden;
|
|
1235
|
+
background: var(--cx-bg);
|
|
1236
|
+
border: 1px solid var(--cx-divider);
|
|
1237
|
+
border-radius: 24px;
|
|
1238
|
+
box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
|
|
1239
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1240
|
+
}
|
|
1241
|
+
.__crossx-card--wallet-selector .__crossx-header {
|
|
1242
|
+
display: flex;
|
|
1243
|
+
align-items: flex-start;
|
|
1244
|
+
justify-content: space-between;
|
|
1245
|
+
gap: 12px;
|
|
1246
|
+
padding: 24px;
|
|
1247
|
+
flex-shrink: 0;
|
|
1248
|
+
}
|
|
1249
|
+
.__crossx-card--wallet-selector > .__crossx-divider {
|
|
1250
|
+
border-top-color: var(--cx-border);
|
|
1251
|
+
flex-shrink: 0;
|
|
1252
|
+
}
|
|
1253
|
+
.__crossx-wallet-sheet-handle {
|
|
1254
|
+
display: none;
|
|
1255
|
+
}
|
|
1256
|
+
.__crossx-wallet-header-copy {
|
|
1257
|
+
display: flex;
|
|
1258
|
+
flex: 1;
|
|
1259
|
+
min-width: 0;
|
|
1260
|
+
flex-direction: column;
|
|
1261
|
+
gap: 4px;
|
|
1262
|
+
padding-right: 16px;
|
|
1263
|
+
}
|
|
1264
|
+
.__crossx-card--wallet-selector .__crossx-title {
|
|
1265
|
+
margin: 0;
|
|
1266
|
+
padding-right: 0;
|
|
1267
|
+
color: var(--cx-title);
|
|
1268
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1269
|
+
font-size: 20px;
|
|
1270
|
+
font-weight: 600;
|
|
1271
|
+
line-height: 1.25;
|
|
1272
|
+
letter-spacing: 0;
|
|
1273
|
+
white-space: nowrap;
|
|
1274
|
+
}
|
|
1275
|
+
.__crossx-card--wallet-selector .__crossx-subtitle--body {
|
|
1276
|
+
margin: 0;
|
|
1277
|
+
color: var(--cx-subtitle);
|
|
1278
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1279
|
+
font-size: 14px;
|
|
1280
|
+
font-weight: 400;
|
|
1281
|
+
line-height: 1.5;
|
|
1282
|
+
letter-spacing: -0.01em;
|
|
1283
|
+
}
|
|
1284
|
+
.__crossx-card--wallet-selector .__crossx-close {
|
|
1285
|
+
position: static;
|
|
1286
|
+
width: 24px;
|
|
1287
|
+
height: 24px;
|
|
1288
|
+
flex-shrink: 0;
|
|
1289
|
+
border-radius: 0;
|
|
1290
|
+
color: var(--cx-label);
|
|
1291
|
+
}
|
|
1292
|
+
.__crossx-card--wallet-selector .__crossx-close svg {
|
|
1293
|
+
width: 24px;
|
|
1294
|
+
height: 24px;
|
|
1295
|
+
}
|
|
1296
|
+
.__crossx-wallet-selector-body {
|
|
1297
|
+
flex: 1;
|
|
1298
|
+
min-height: 0;
|
|
1299
|
+
overflow-y: auto;
|
|
1300
|
+
padding: 0;
|
|
1301
|
+
gap: 0;
|
|
1302
|
+
}
|
|
1303
|
+
.__crossx-wallet-list-section {
|
|
1304
|
+
display: flex;
|
|
1305
|
+
flex-direction: column;
|
|
1306
|
+
gap: 8px;
|
|
1307
|
+
width: 100%;
|
|
1308
|
+
padding: 24px 24px 12px;
|
|
1309
|
+
box-sizing: border-box;
|
|
1310
|
+
}
|
|
1311
|
+
.__crossx-wallet-help-section {
|
|
1312
|
+
width: 100%;
|
|
1313
|
+
padding: 12px 24px 24px;
|
|
1314
|
+
box-sizing: border-box;
|
|
1315
|
+
}
|
|
1207
1316
|
.__crossx-wallet-list {
|
|
1208
1317
|
display: flex;
|
|
1209
1318
|
flex-direction: column;
|
|
@@ -1230,10 +1339,12 @@ button.__crossx-connect-other-block:active {
|
|
|
1230
1339
|
.__crossx-wallet-item {
|
|
1231
1340
|
display: flex;
|
|
1232
1341
|
align-items: center;
|
|
1233
|
-
|
|
1234
|
-
|
|
1342
|
+
justify-content: space-between;
|
|
1343
|
+
gap: 8px;
|
|
1344
|
+
min-height: 66px;
|
|
1345
|
+
padding: 12px 16px;
|
|
1235
1346
|
background: var(--cx-pill-bg);
|
|
1236
|
-
border:
|
|
1347
|
+
border: none;
|
|
1237
1348
|
border-radius: 12px;
|
|
1238
1349
|
cursor: pointer;
|
|
1239
1350
|
appearance: none;
|
|
@@ -1243,10 +1354,10 @@ button.__crossx-connect-other-block:active {
|
|
|
1243
1354
|
outline: none;
|
|
1244
1355
|
width: 100%;
|
|
1245
1356
|
text-align: left;
|
|
1246
|
-
font-family: '
|
|
1357
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1247
1358
|
}
|
|
1248
1359
|
.__crossx-wallet-item--selected {
|
|
1249
|
-
border-color:
|
|
1360
|
+
border-color: transparent;
|
|
1250
1361
|
}
|
|
1251
1362
|
.__crossx-wallet-item:hover,
|
|
1252
1363
|
.__crossx-wallet-item:focus,
|
|
@@ -1259,15 +1370,15 @@ button.__crossx-connect-other-block:active {
|
|
|
1259
1370
|
background: var(--cx-pill-bg) !important;
|
|
1260
1371
|
}
|
|
1261
1372
|
.__crossx-wallet-avatar {
|
|
1262
|
-
width:
|
|
1263
|
-
height:
|
|
1373
|
+
width: 28px;
|
|
1374
|
+
height: 28px;
|
|
1264
1375
|
flex-shrink: 0;
|
|
1265
1376
|
border-radius: 50%;
|
|
1266
1377
|
overflow: hidden;
|
|
1267
1378
|
display: flex;
|
|
1268
1379
|
align-items: center;
|
|
1269
1380
|
justify-content: center;
|
|
1270
|
-
background:
|
|
1381
|
+
background: transparent;
|
|
1271
1382
|
}
|
|
1272
1383
|
.__crossx-wallet-avatar-img {
|
|
1273
1384
|
width: 28px;
|
|
@@ -1291,47 +1402,46 @@ button.__crossx-connect-other-block:active {
|
|
|
1291
1402
|
display: flex;
|
|
1292
1403
|
flex-direction: column;
|
|
1293
1404
|
align-items: flex-start;
|
|
1294
|
-
gap:
|
|
1405
|
+
gap: 0;
|
|
1295
1406
|
min-width: 0;
|
|
1296
1407
|
flex: 1;
|
|
1297
1408
|
}
|
|
1298
1409
|
.__crossx-wallet-idx {
|
|
1299
|
-
font-size:
|
|
1410
|
+
font-size: 16px;
|
|
1300
1411
|
font-weight: 600;
|
|
1301
|
-
line-height: 1.
|
|
1412
|
+
line-height: 1.5;
|
|
1302
1413
|
color: var(--cx-value);
|
|
1414
|
+
letter-spacing: -0.01em;
|
|
1415
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1303
1416
|
white-space: nowrap;
|
|
1304
1417
|
overflow: hidden;
|
|
1305
1418
|
text-overflow: ellipsis;
|
|
1306
1419
|
max-width: 100%;
|
|
1307
1420
|
}
|
|
1308
1421
|
.__crossx-wallet-addr {
|
|
1309
|
-
font-size:
|
|
1422
|
+
font-size: 12px;
|
|
1310
1423
|
font-weight: 400;
|
|
1311
|
-
line-height: 1.
|
|
1312
|
-
color: var(--cx-
|
|
1424
|
+
line-height: 1.5;
|
|
1425
|
+
color: var(--cx-subtitle);
|
|
1426
|
+
letter-spacing: -0.01em;
|
|
1427
|
+
font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
1313
1428
|
white-space: nowrap;
|
|
1314
1429
|
}
|
|
1315
1430
|
.__crossx-wallet-selected {
|
|
1316
|
-
|
|
1317
|
-
font-weight: 600;
|
|
1318
|
-
line-height: 1.3;
|
|
1319
|
-
color: #ffffff;
|
|
1320
|
-
background: var(--cx-primary);
|
|
1321
|
-
border-radius: 4px;
|
|
1322
|
-
padding: 4px 8px;
|
|
1323
|
-
margin-left: auto;
|
|
1324
|
-
flex-shrink: 0;
|
|
1325
|
-
white-space: nowrap;
|
|
1326
|
-
display: flex;
|
|
1327
|
-
align-items: center;
|
|
1431
|
+
display: none;
|
|
1328
1432
|
}
|
|
1329
1433
|
.__crossx-wallet-check {
|
|
1330
|
-
display:
|
|
1434
|
+
display: flex;
|
|
1331
1435
|
flex-shrink: 0;
|
|
1332
1436
|
margin-left: auto;
|
|
1333
|
-
width:
|
|
1334
|
-
height:
|
|
1437
|
+
width: 20px;
|
|
1438
|
+
height: 20px;
|
|
1439
|
+
align-items: center;
|
|
1440
|
+
justify-content: center;
|
|
1441
|
+
}
|
|
1442
|
+
.__crossx-wallet-check svg {
|
|
1443
|
+
width: 20px;
|
|
1444
|
+
height: 20px;
|
|
1335
1445
|
}
|
|
1336
1446
|
.__crossx-wallet-add {
|
|
1337
1447
|
display: flex;
|
|
@@ -1340,7 +1450,7 @@ button.__crossx-connect-other-block:active {
|
|
|
1340
1450
|
gap: 8px;
|
|
1341
1451
|
padding: 16px;
|
|
1342
1452
|
border: 1px dashed var(--cx-divider);
|
|
1343
|
-
border-radius:
|
|
1453
|
+
border-radius: 12px;
|
|
1344
1454
|
cursor: pointer;
|
|
1345
1455
|
appearance: none;
|
|
1346
1456
|
-webkit-appearance: none;
|
|
@@ -1350,7 +1460,8 @@ button.__crossx-connect-other-block:active {
|
|
|
1350
1460
|
background: none;
|
|
1351
1461
|
width: 100%;
|
|
1352
1462
|
flex-shrink: 0;
|
|
1353
|
-
|
|
1463
|
+
color: var(--cx-value);
|
|
1464
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1354
1465
|
}
|
|
1355
1466
|
.__crossx-wallet-add:hover,
|
|
1356
1467
|
.__crossx-wallet-add:focus,
|
|
@@ -1366,13 +1477,14 @@ button.__crossx-connect-other-block:active {
|
|
|
1366
1477
|
.__crossx-wallet-add-icon {
|
|
1367
1478
|
width: 24px;
|
|
1368
1479
|
height: 24px;
|
|
1369
|
-
color: var(--cx-
|
|
1480
|
+
color: var(--cx-label);
|
|
1370
1481
|
}
|
|
1371
1482
|
.__crossx-wallet-add-label {
|
|
1372
1483
|
font-size: 16px;
|
|
1373
|
-
font-weight:
|
|
1374
|
-
line-height: 1.
|
|
1375
|
-
|
|
1484
|
+
font-weight: 500;
|
|
1485
|
+
line-height: 1.5;
|
|
1486
|
+
letter-spacing: -0.01em;
|
|
1487
|
+
color: var(--cx-value);
|
|
1376
1488
|
}
|
|
1377
1489
|
.__crossx-wallet-add-error {
|
|
1378
1490
|
margin: 8px 0 0;
|
|
@@ -1386,6 +1498,30 @@ button.__crossx-connect-other-block:active {
|
|
|
1386
1498
|
word-break: break-word;
|
|
1387
1499
|
}
|
|
1388
1500
|
.__crossx-wallet-add-error[hidden] { display: none; }
|
|
1501
|
+
.__crossx-wallet-help-section .__crossx-mig-info {
|
|
1502
|
+
gap: 6px;
|
|
1503
|
+
padding: 12px;
|
|
1504
|
+
background: var(--cx-pill-bg);
|
|
1505
|
+
border: 1px solid var(--cx-border);
|
|
1506
|
+
border-radius: 12px;
|
|
1507
|
+
box-sizing: border-box;
|
|
1508
|
+
}
|
|
1509
|
+
.__crossx-wallet-help-section .__crossx-mig-info-title {
|
|
1510
|
+
color: var(--cx-value);
|
|
1511
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1512
|
+
font-size: 14px;
|
|
1513
|
+
font-weight: 600;
|
|
1514
|
+
line-height: 1.5;
|
|
1515
|
+
letter-spacing: -0.01em;
|
|
1516
|
+
}
|
|
1517
|
+
.__crossx-wallet-help-section .__crossx-mig-info-desc {
|
|
1518
|
+
color: var(--cx-subtitle);
|
|
1519
|
+
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
|
|
1520
|
+
font-size: 12px;
|
|
1521
|
+
font-weight: 400;
|
|
1522
|
+
line-height: 1.5;
|
|
1523
|
+
letter-spacing: -0.01em;
|
|
1524
|
+
}
|
|
1389
1525
|
|
|
1390
1526
|
/* ── Safe area fill (mobile only, created by JS in mountOverlay) ── */
|
|
1391
1527
|
.__crossx-safe-area-fill {
|
|
@@ -1393,7 +1529,7 @@ button.__crossx-connect-other-block:active {
|
|
|
1393
1529
|
}
|
|
1394
1530
|
/* ── Mobile bottom sheet ───────────────────────────────────── */
|
|
1395
1531
|
@media (max-width: 480px) {
|
|
1396
|
-
#${
|
|
1532
|
+
#${Q} {
|
|
1397
1533
|
align-items: flex-end;
|
|
1398
1534
|
/*
|
|
1399
1535
|
* iOS Safari 는 soft keyboard 가 떠도 layout viewport 를 축소시키지 않아
|
|
@@ -1431,37 +1567,88 @@ button.__crossx-connect-other-block:active {
|
|
|
1431
1567
|
overflow: hidden !important;
|
|
1432
1568
|
display: flex !important;
|
|
1433
1569
|
flex-direction: column !important;
|
|
1570
|
+
border: 1px solid var(--cx-divider) !important;
|
|
1571
|
+
border-bottom: none !important;
|
|
1572
|
+
border-radius: 24px 24px 0 0 !important;
|
|
1573
|
+
max-height: 85vh;
|
|
1574
|
+
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 20px);
|
|
1434
1575
|
}
|
|
1435
|
-
.__crossx-card--wallet-selector .__crossx-header {
|
|
1436
|
-
|
|
1437
|
-
.__crossx-card--wallet-selector .__crossx-body {
|
|
1438
|
-
flex: 1;
|
|
1439
|
-
min-height: 0;
|
|
1440
|
-
overflow: hidden;
|
|
1441
|
-
display: flex;
|
|
1576
|
+
.__crossx-card--wallet-selector .__crossx-header {
|
|
1577
|
+
flex-shrink: 0;
|
|
1442
1578
|
flex-direction: column;
|
|
1579
|
+
align-items: center;
|
|
1580
|
+
gap: 16px;
|
|
1581
|
+
padding: 16px;
|
|
1443
1582
|
}
|
|
1444
|
-
.__crossx-card--wallet-selector .__crossx-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1583
|
+
.__crossx-card--wallet-selector > .__crossx-divider { flex-shrink: 0; }
|
|
1584
|
+
.__crossx-wallet-sheet-handle {
|
|
1585
|
+
display: block;
|
|
1586
|
+
width: 30px;
|
|
1587
|
+
height: 6px;
|
|
1588
|
+
border-radius: 9999px;
|
|
1589
|
+
background: var(--cx-surface-subtle);
|
|
1590
|
+
flex-shrink: 0;
|
|
1449
1591
|
}
|
|
1450
|
-
.__crossx-
|
|
1451
|
-
|
|
1592
|
+
.__crossx-wallet-header-copy {
|
|
1593
|
+
width: 100%;
|
|
1594
|
+
padding-right: 0;
|
|
1595
|
+
}
|
|
1596
|
+
.__crossx-card--wallet-selector .__crossx-close {
|
|
1597
|
+
display: none;
|
|
1598
|
+
}
|
|
1599
|
+
.__crossx-card--wallet-selector .__crossx-body,
|
|
1600
|
+
.__crossx-card--wallet-selector .__crossx-wallet-selector-body {
|
|
1452
1601
|
flex: 1;
|
|
1453
1602
|
min-height: 0;
|
|
1603
|
+
overflow-y: auto;
|
|
1454
1604
|
display: flex;
|
|
1455
1605
|
flex-direction: column;
|
|
1456
1606
|
}
|
|
1607
|
+
.__crossx-wallet-list-section { padding: 24px 16px 12px; }
|
|
1608
|
+
.__crossx-wallet-help-section { padding: 12px 16px 16px; }
|
|
1457
1609
|
.__crossx-card--wallet-selector .__crossx-wallet-list {
|
|
1458
|
-
flex: 1;
|
|
1459
|
-
min-height: 0;
|
|
1460
1610
|
max-height: 203px;
|
|
1461
1611
|
}
|
|
1462
|
-
.__crossx-card--wallet-
|
|
1463
|
-
|
|
1464
|
-
|
|
1612
|
+
.__crossx-card--wallet-created {
|
|
1613
|
+
width: 100% !important;
|
|
1614
|
+
max-width: 100% !important;
|
|
1615
|
+
border-radius: 24px 24px 0 0 !important;
|
|
1616
|
+
border: 1px solid var(--cx-border-medium) !important;
|
|
1617
|
+
border-bottom: none !important;
|
|
1618
|
+
padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 20px);
|
|
1619
|
+
}
|
|
1620
|
+
.__crossx-card--wallet-created .__crossx-header {
|
|
1621
|
+
display: flex;
|
|
1622
|
+
flex-direction: column;
|
|
1623
|
+
align-items: center;
|
|
1624
|
+
gap: 16px;
|
|
1625
|
+
padding: 16px;
|
|
1626
|
+
border-bottom: 1px solid var(--cx-border);
|
|
1627
|
+
}
|
|
1628
|
+
.__crossx-card--wallet-created .__crossx-title {
|
|
1629
|
+
width: 100%;
|
|
1630
|
+
padding-right: 0 !important;
|
|
1631
|
+
}
|
|
1632
|
+
.__crossx-card--wallet-created .__crossx-close {
|
|
1633
|
+
display: none;
|
|
1634
|
+
}
|
|
1635
|
+
.__crossx-wallet-created-sheet-handle {
|
|
1636
|
+
display: block;
|
|
1637
|
+
width: 30px;
|
|
1638
|
+
height: 6px;
|
|
1639
|
+
border-radius: 9999px;
|
|
1640
|
+
background: var(--cx-surface-high);
|
|
1641
|
+
flex-shrink: 0;
|
|
1642
|
+
}
|
|
1643
|
+
.__crossx-wallet-created-body {
|
|
1644
|
+
padding: 20px 16px;
|
|
1645
|
+
}
|
|
1646
|
+
.__crossx-wallet-created-hero {
|
|
1647
|
+
height: 285px;
|
|
1648
|
+
}
|
|
1649
|
+
.__crossx-wallet-created-footer {
|
|
1650
|
+
padding: 12px 16px 16px;
|
|
1651
|
+
}
|
|
1465
1652
|
.__crossx-card--send-tx,
|
|
1466
1653
|
.__crossx-card--sign-tx,
|
|
1467
1654
|
.__crossx-card--sign-msg,
|
|
@@ -1535,20 +1722,40 @@ button.__crossx-connect-other-block:active {
|
|
|
1535
1722
|
.__crossx-card--pin6 {
|
|
1536
1723
|
width: 100% !important;
|
|
1537
1724
|
max-width: 100% !important;
|
|
1538
|
-
border-radius:
|
|
1539
|
-
border: 1px solid var(--cx-border) !important;
|
|
1725
|
+
border-radius: 24px 24px 0 0 !important;
|
|
1726
|
+
border: 1px solid var(--cx-border-medium) !important;
|
|
1540
1727
|
border-bottom: none !important;
|
|
1541
1728
|
max-height: 92vh;
|
|
1542
1729
|
overflow: hidden;
|
|
1543
1730
|
display: flex;
|
|
1544
1731
|
flex-direction: column;
|
|
1732
|
+
box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
|
|
1545
1733
|
}
|
|
1546
1734
|
.__crossx-card--pin6 > .__crossx-divider { display: none; }
|
|
1547
1735
|
.__crossx-card--pin6 .__crossx-header {
|
|
1548
|
-
|
|
1736
|
+
display: flex;
|
|
1737
|
+
flex-direction: column;
|
|
1738
|
+
align-items: center;
|
|
1739
|
+
gap: 16px;
|
|
1740
|
+
padding: 16px;
|
|
1741
|
+
flex-shrink: 0;
|
|
1742
|
+
border-bottom: 1px solid var(--cx-border);
|
|
1743
|
+
}
|
|
1744
|
+
.__crossx-card--pin6 .__crossx-title {
|
|
1745
|
+
width: 100%;
|
|
1746
|
+
font-size: 20px;
|
|
1747
|
+
margin-bottom: 0;
|
|
1748
|
+
padding-right: 0 !important;
|
|
1749
|
+
}
|
|
1750
|
+
.__crossx-card--pin6 .__crossx-close { display: none; }
|
|
1751
|
+
.__crossx-pin6-sheet-handle {
|
|
1752
|
+
display: block;
|
|
1753
|
+
width: 30px;
|
|
1754
|
+
height: 6px;
|
|
1755
|
+
border-radius: 9999px;
|
|
1756
|
+
background: var(--cx-surface-high);
|
|
1549
1757
|
flex-shrink: 0;
|
|
1550
1758
|
}
|
|
1551
|
-
.__crossx-card--pin6 .__crossx-title { font-size: 16px; margin-bottom: 0; }
|
|
1552
1759
|
.__crossx-card--pin6 .__crossx-pw-subtitle { display: none; }
|
|
1553
1760
|
/* Notice 화면 body (pw-body) */
|
|
1554
1761
|
.__crossx-card--pin6 .__crossx-pw-body {
|
|
@@ -1556,8 +1763,8 @@ button.__crossx-connect-other-block:active {
|
|
|
1556
1763
|
min-height: 0;
|
|
1557
1764
|
overflow-y: auto;
|
|
1558
1765
|
-webkit-overflow-scrolling: touch;
|
|
1559
|
-
padding: 16px
|
|
1560
|
-
gap:
|
|
1766
|
+
padding: 16px;
|
|
1767
|
+
gap: 32px;
|
|
1561
1768
|
}
|
|
1562
1769
|
.__crossx-card--pin6 .__crossx-pw-fields--notice {
|
|
1563
1770
|
flex: 1;
|
|
@@ -1565,16 +1772,19 @@ button.__crossx-connect-other-block:active {
|
|
|
1565
1772
|
overflow-y: auto;
|
|
1566
1773
|
-webkit-overflow-scrolling: touch;
|
|
1567
1774
|
}
|
|
1568
|
-
.__crossx-card--pin6 .__crossx-pw-notice-title { font-size:
|
|
1775
|
+
.__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 18px; }
|
|
1569
1776
|
.__crossx-card--pin6 .__crossx-pw-notice-icon { width: 20px; height: 20px; }
|
|
1570
1777
|
.__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
|
|
1778
|
+
.__crossx-card--pin6 .__crossx-pin6-footer {
|
|
1779
|
+
padding: 12px 16px 16px;
|
|
1780
|
+
}
|
|
1571
1781
|
/* PIN 입력 body */
|
|
1572
1782
|
.__crossx-card--pin6 .__crossx-pin6-body {
|
|
1573
1783
|
flex: 1;
|
|
1574
1784
|
min-height: 0;
|
|
1575
1785
|
overflow-y: auto;
|
|
1576
1786
|
-webkit-overflow-scrolling: touch;
|
|
1577
|
-
padding: 16px
|
|
1787
|
+
padding: 40px 16px;
|
|
1578
1788
|
gap: 16px;
|
|
1579
1789
|
}
|
|
1580
1790
|
/* PIN 넘패드 활성화 */
|
|
@@ -1618,12 +1828,11 @@ button.__crossx-connect-other-block:active {
|
|
|
1618
1828
|
|
|
1619
1829
|
/* ── Landscape for signing/transaction modals ──────────── */
|
|
1620
1830
|
@media (orientation: landscape) and (max-height: 500px) {
|
|
1621
|
-
#${
|
|
1831
|
+
#${Q} { align-items: center !important; overflow: hidden; }
|
|
1622
1832
|
.__crossx-card--send-tx,
|
|
1623
1833
|
.__crossx-card--sign-tx,
|
|
1624
1834
|
.__crossx-card--sign-msg,
|
|
1625
|
-
.__crossx-card--sign-typed
|
|
1626
|
-
.__crossx-card--wallet-selector {
|
|
1835
|
+
.__crossx-card--sign-typed {
|
|
1627
1836
|
width: 600px;
|
|
1628
1837
|
max-width: calc(100vw - 32px);
|
|
1629
1838
|
border-radius: 24px;
|
|
@@ -1635,23 +1844,20 @@ button.__crossx-connect-other-block:active {
|
|
|
1635
1844
|
.__crossx-card--send-tx .__crossx-header,
|
|
1636
1845
|
.__crossx-card--sign-tx .__crossx-header,
|
|
1637
1846
|
.__crossx-card--sign-msg .__crossx-header,
|
|
1638
|
-
.__crossx-card--sign-typed .__crossx-header
|
|
1639
|
-
.__crossx-card--wallet-selector .__crossx-header {
|
|
1847
|
+
.__crossx-card--sign-typed .__crossx-header {
|
|
1640
1848
|
padding: 16px 24px 12px;
|
|
1641
1849
|
}
|
|
1642
1850
|
.__crossx-card--send-tx .__crossx-body,
|
|
1643
1851
|
.__crossx-card--sign-tx .__crossx-body,
|
|
1644
1852
|
.__crossx-card--sign-msg .__crossx-body,
|
|
1645
|
-
.__crossx-card--sign-typed .__crossx-body
|
|
1646
|
-
.__crossx-card--wallet-selector .__crossx-body {
|
|
1853
|
+
.__crossx-card--sign-typed .__crossx-body {
|
|
1647
1854
|
padding: 16px 24px 20px;
|
|
1648
1855
|
gap: 12px;
|
|
1649
1856
|
}
|
|
1650
1857
|
.__crossx-card--send-tx .__crossx-body-cols,
|
|
1651
1858
|
.__crossx-card--sign-tx .__crossx-body-cols,
|
|
1652
1859
|
.__crossx-card--sign-msg .__crossx-body-cols,
|
|
1653
|
-
.__crossx-card--sign-typed .__crossx-body-cols
|
|
1654
|
-
.__crossx-card--wallet-selector .__crossx-body-cols {
|
|
1860
|
+
.__crossx-card--sign-typed .__crossx-body-cols {
|
|
1655
1861
|
flex-direction: row;
|
|
1656
1862
|
gap: 24px;
|
|
1657
1863
|
align-items: stretch;
|
|
@@ -1675,39 +1881,6 @@ button.__crossx-connect-other-block:active {
|
|
|
1675
1881
|
.__crossx-card--sign-msg .__crossx-msg-box { max-height: none; overflow-y: auto; }
|
|
1676
1882
|
.__crossx-card--sign-typed .__crossx-td-rows { max-height: none; overflow-y: auto; }
|
|
1677
1883
|
.__crossx-col-left > .__crossx-divider { display: none; }
|
|
1678
|
-
.__crossx-card--wallet-selector {
|
|
1679
|
-
overflow: hidden !important;
|
|
1680
|
-
display: flex !important;
|
|
1681
|
-
flex-direction: column !important;
|
|
1682
|
-
}
|
|
1683
|
-
.__crossx-card--wallet-selector .__crossx-header { flex-shrink: 0; }
|
|
1684
|
-
.__crossx-card--wallet-selector > .__crossx-divider { flex-shrink: 0; }
|
|
1685
|
-
.__crossx-card--wallet-selector .__crossx-body {
|
|
1686
|
-
flex: 1;
|
|
1687
|
-
min-height: 0;
|
|
1688
|
-
overflow: hidden;
|
|
1689
|
-
display: flex;
|
|
1690
|
-
flex-direction: column;
|
|
1691
|
-
}
|
|
1692
|
-
.__crossx-card--wallet-selector .__crossx-body-cols {
|
|
1693
|
-
flex: 1;
|
|
1694
|
-
min-height: 0;
|
|
1695
|
-
align-items: stretch !important;
|
|
1696
|
-
}
|
|
1697
|
-
.__crossx-card--wallet-selector .__crossx-col-right-ws {
|
|
1698
|
-
display: flex;
|
|
1699
|
-
flex-direction: column;
|
|
1700
|
-
gap: 8px;
|
|
1701
|
-
min-height: 0;
|
|
1702
|
-
overflow: hidden;
|
|
1703
|
-
}
|
|
1704
|
-
.__crossx-card--wallet-selector .__crossx-wallet-list {
|
|
1705
|
-
max-height: none;
|
|
1706
|
-
flex: 1;
|
|
1707
|
-
min-height: 0;
|
|
1708
|
-
}
|
|
1709
|
-
.__crossx-card--wallet-selector .__crossx-wallet-add { flex-shrink: 0; }
|
|
1710
|
-
|
|
1711
1884
|
/* ── Password / Notice modal landscape ─────────────────────────── */
|
|
1712
1885
|
.__crossx-card--password {
|
|
1713
1886
|
width: 640px;
|
|
@@ -1766,10 +1939,10 @@ button.__crossx-connect-other-block:active {
|
|
|
1766
1939
|
|
|
1767
1940
|
/* ── PIN6 랜드스케이프 ─────────────────────────── */
|
|
1768
1941
|
.__crossx-card--pin6 {
|
|
1769
|
-
width:
|
|
1942
|
+
width: 600px;
|
|
1770
1943
|
max-width: calc(100vw - 32px);
|
|
1771
1944
|
border-radius: 24px;
|
|
1772
|
-
border
|
|
1945
|
+
border: 1px solid var(--cx-border-medium);
|
|
1773
1946
|
max-height: calc(100vh - 32px);
|
|
1774
1947
|
overflow: hidden;
|
|
1775
1948
|
display: flex;
|
|
@@ -1777,14 +1950,14 @@ button.__crossx-connect-other-block:active {
|
|
|
1777
1950
|
animation: __crossx-slide-up 0.18s ease;
|
|
1778
1951
|
}
|
|
1779
1952
|
.__crossx-card--pin6 > .__crossx-divider { flex-shrink: 0; }
|
|
1780
|
-
.__crossx-card--pin6 .__crossx-header { flex-shrink: 0; padding: 16px
|
|
1953
|
+
.__crossx-card--pin6 .__crossx-header { flex-shrink: 0; padding: 16px; }
|
|
1781
1954
|
.__crossx-card--pin6 .__crossx-pw-body {
|
|
1782
1955
|
flex: 1;
|
|
1783
1956
|
min-height: 0;
|
|
1784
1957
|
overflow-y: auto;
|
|
1785
1958
|
-webkit-overflow-scrolling: touch;
|
|
1786
|
-
padding: 16px
|
|
1787
|
-
gap:
|
|
1959
|
+
padding: 16px;
|
|
1960
|
+
gap: 32px;
|
|
1788
1961
|
}
|
|
1789
1962
|
.__crossx-card--pin6 .__crossx-pw-fields {
|
|
1790
1963
|
gap: 16px;
|
|
@@ -1795,50 +1968,110 @@ button.__crossx-connect-other-block:active {
|
|
|
1795
1968
|
overflow-y: auto;
|
|
1796
1969
|
-webkit-overflow-scrolling: touch;
|
|
1797
1970
|
}
|
|
1798
|
-
.__crossx-card--pin6 .__crossx-pw-notice-title { font-size:
|
|
1971
|
+
.__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 18px; }
|
|
1799
1972
|
.__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
|
|
1800
1973
|
.__crossx-card--pin6 .__crossx-pin6-body {
|
|
1801
1974
|
flex: 1;
|
|
1802
1975
|
min-height: 0;
|
|
1803
1976
|
overflow-y: auto;
|
|
1804
|
-
padding: 16px
|
|
1805
|
-
gap:
|
|
1977
|
+
padding: 16px;
|
|
1978
|
+
gap: 16px;
|
|
1806
1979
|
}
|
|
1807
1980
|
.__crossx-card--pin6 .__crossx-pin6-next { flex-shrink: 0; }
|
|
1981
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) {
|
|
1982
|
+
display: grid;
|
|
1983
|
+
grid-template-columns: 1fr 1fr;
|
|
1984
|
+
grid-template-rows: auto auto 1fr;
|
|
1985
|
+
}
|
|
1986
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-header,
|
|
1987
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) > .__crossx-divider {
|
|
1988
|
+
grid-column: 1 / -1;
|
|
1989
|
+
}
|
|
1990
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-body {
|
|
1991
|
+
grid-column: 1;
|
|
1992
|
+
grid-row: 3;
|
|
1993
|
+
justify-content: center;
|
|
1994
|
+
align-items: center;
|
|
1995
|
+
overflow: hidden;
|
|
1996
|
+
}
|
|
1997
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-numpad {
|
|
1998
|
+
grid-column: 2;
|
|
1999
|
+
grid-row: 3;
|
|
2000
|
+
display: flex !important;
|
|
2001
|
+
padding: 16px 10px;
|
|
2002
|
+
gap: 4px;
|
|
2003
|
+
overflow: hidden;
|
|
2004
|
+
}
|
|
2005
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-box,
|
|
2006
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-dot {
|
|
2007
|
+
width: 36px;
|
|
2008
|
+
height: 36px;
|
|
2009
|
+
font-size: 16px;
|
|
2010
|
+
}
|
|
2011
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-numpad-row {
|
|
2012
|
+
gap: 4px;
|
|
2013
|
+
}
|
|
2014
|
+
.__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-numpad-key {
|
|
2015
|
+
height: 43.5px;
|
|
2016
|
+
max-width: none;
|
|
2017
|
+
border-radius: 4px;
|
|
2018
|
+
font-size: 18px;
|
|
2019
|
+
}
|
|
1808
2020
|
}
|
|
1809
2021
|
|
|
1810
2022
|
/* ── 6-digit wallet PIN box input ──────────────────────────────────── */
|
|
1811
2023
|
.__crossx-card--pin6 {
|
|
1812
2024
|
width: 100%;
|
|
1813
|
-
max-width:
|
|
2025
|
+
max-width: 540px;
|
|
1814
2026
|
}
|
|
1815
|
-
|
|
2027
|
+
.__crossx-pin6-sheet-handle {
|
|
2028
|
+
display: none;
|
|
2029
|
+
}
|
|
2030
|
+
/* PIN6 Notice 화면 body/fields: Figma 기준 px-24 */
|
|
1816
2031
|
.__crossx-card--pin6 .__crossx-pw-body {
|
|
1817
|
-
padding:
|
|
1818
|
-
gap:
|
|
2032
|
+
padding: 24px;
|
|
2033
|
+
gap: 32px;
|
|
1819
2034
|
}
|
|
1820
2035
|
.__crossx-card--pin6 .__crossx-pw-fields {
|
|
1821
|
-
gap:
|
|
2036
|
+
gap: 32px;
|
|
2037
|
+
}
|
|
2038
|
+
.__crossx-pin6-footer {
|
|
2039
|
+
display: flex;
|
|
2040
|
+
flex-direction: column;
|
|
2041
|
+
align-items: center;
|
|
2042
|
+
justify-content: center;
|
|
2043
|
+
width: 100%;
|
|
2044
|
+
padding: 12px 24px 24px;
|
|
2045
|
+
background: var(--cx-bg);
|
|
2046
|
+
box-sizing: border-box;
|
|
2047
|
+
}
|
|
2048
|
+
.__crossx-card--pin6 .__crossx-pw-btn.--disabled {
|
|
2049
|
+
background: var(--cx-primary);
|
|
2050
|
+
color: var(--cx-on-primary);
|
|
2051
|
+
opacity: 1;
|
|
2052
|
+
cursor: pointer;
|
|
1822
2053
|
}
|
|
1823
2054
|
.__crossx-pin6-header-sub {
|
|
1824
2055
|
font-size: 14px;
|
|
1825
2056
|
font-weight: 400;
|
|
1826
2057
|
color: var(--cx-subtitle);
|
|
1827
|
-
line-height: 1.
|
|
1828
|
-
margin:
|
|
2058
|
+
line-height: 1.5;
|
|
2059
|
+
margin: 0;
|
|
2060
|
+
letter-spacing: -0.01em;
|
|
1829
2061
|
}
|
|
1830
2062
|
.__crossx-pin6-body {
|
|
1831
2063
|
display: flex;
|
|
1832
2064
|
flex-direction: column;
|
|
1833
2065
|
align-items: center;
|
|
1834
|
-
padding:
|
|
2066
|
+
padding: 40px 24px 72px;
|
|
1835
2067
|
gap: 16px;
|
|
1836
2068
|
width: 100%;
|
|
2069
|
+
box-sizing: border-box;
|
|
1837
2070
|
}
|
|
1838
2071
|
.__crossx-pin6-subtitle {
|
|
1839
|
-
font-size:
|
|
1840
|
-
font-weight:
|
|
1841
|
-
color: var(--cx-
|
|
2072
|
+
font-size: 14px;
|
|
2073
|
+
font-weight: 400;
|
|
2074
|
+
color: var(--cx-subtitle);
|
|
1842
2075
|
text-align: center;
|
|
1843
2076
|
margin: 0;
|
|
1844
2077
|
line-height: 1.5;
|
|
@@ -1853,12 +2086,12 @@ button.__crossx-connect-other-block:active {
|
|
|
1853
2086
|
padding: 8px 0;
|
|
1854
2087
|
}
|
|
1855
2088
|
.__crossx-pin6-box {
|
|
1856
|
-
width: 48px;
|
|
1857
|
-
height: 48px;
|
|
2089
|
+
width: clamp(36px, 12vw, 48px);
|
|
2090
|
+
height: clamp(36px, 12vw, 48px);
|
|
1858
2091
|
border-radius: 12px;
|
|
1859
2092
|
border: none;
|
|
1860
2093
|
background: var(--cx-input-bg);
|
|
1861
|
-
font-size:
|
|
2094
|
+
font-size: 20px;
|
|
1862
2095
|
font-weight: 600;
|
|
1863
2096
|
text-align: center;
|
|
1864
2097
|
color: var(--cx-value);
|
|
@@ -1896,9 +2129,14 @@ button.__crossx-connect-other-block:active {
|
|
|
1896
2129
|
color: var(--cx-error);
|
|
1897
2130
|
text-align: center;
|
|
1898
2131
|
margin: 0;
|
|
1899
|
-
|
|
1900
|
-
line-height: 1.4;
|
|
2132
|
+
line-height: 1.5;
|
|
1901
2133
|
width: 100%;
|
|
2134
|
+
letter-spacing: -0.01em;
|
|
2135
|
+
}
|
|
2136
|
+
.__crossx-pin6-error:empty,
|
|
2137
|
+
.__crossx-pin6-warning:empty,
|
|
2138
|
+
.__crossx-pin6-attempt:empty {
|
|
2139
|
+
display: none;
|
|
1902
2140
|
}
|
|
1903
2141
|
/* 잠금 메시지 + 카운트다운 */
|
|
1904
2142
|
.__crossx-pin6-lock-msg {
|
|
@@ -1963,8 +2201,8 @@ button.__crossx-connect-other-block:active {
|
|
|
1963
2201
|
padding: 8px 0;
|
|
1964
2202
|
}
|
|
1965
2203
|
.__crossx-pin6-dot {
|
|
1966
|
-
width: 48px;
|
|
1967
|
-
height: 48px;
|
|
2204
|
+
width: clamp(36px, 12vw, 48px);
|
|
2205
|
+
height: clamp(36px, 12vw, 48px);
|
|
1968
2206
|
border-radius: 12px;
|
|
1969
2207
|
background: var(--cx-input-bg);
|
|
1970
2208
|
display: flex;
|
|
@@ -2114,6 +2352,224 @@ button.__crossx-connect-other-block:active {
|
|
|
2114
2352
|
margin: 0;
|
|
2115
2353
|
}
|
|
2116
2354
|
|
|
2355
|
+
/* ── Wallet Created Modal ───────────────────────────────────── */
|
|
2356
|
+
.__crossx-card--wallet-created {
|
|
2357
|
+
width: 540px;
|
|
2358
|
+
max-width: calc(100vw - 32px);
|
|
2359
|
+
display: flex;
|
|
2360
|
+
flex-direction: column;
|
|
2361
|
+
}
|
|
2362
|
+
.__crossx-wallet-created-sheet-handle {
|
|
2363
|
+
display: none;
|
|
2364
|
+
}
|
|
2365
|
+
.__crossx-wallet-created-body {
|
|
2366
|
+
padding: 24px;
|
|
2367
|
+
width: 100%;
|
|
2368
|
+
box-sizing: border-box;
|
|
2369
|
+
}
|
|
2370
|
+
.__crossx-wallet-created-hero {
|
|
2371
|
+
height: 285px;
|
|
2372
|
+
display: flex;
|
|
2373
|
+
align-items: center;
|
|
2374
|
+
justify-content: center;
|
|
2375
|
+
width: 100%;
|
|
2376
|
+
}
|
|
2377
|
+
.__crossx-wallet-created-illust {
|
|
2378
|
+
display: block;
|
|
2379
|
+
width: 204px;
|
|
2380
|
+
height: 156px;
|
|
2381
|
+
position: relative;
|
|
2382
|
+
}
|
|
2383
|
+
.__crossx-wallet-created-shadow {
|
|
2384
|
+
position: absolute;
|
|
2385
|
+
left: 60px;
|
|
2386
|
+
bottom: 7px;
|
|
2387
|
+
width: 84px;
|
|
2388
|
+
height: 22px;
|
|
2389
|
+
border-radius: 50%;
|
|
2390
|
+
background: rgba(0,0,0,0.65);
|
|
2391
|
+
}
|
|
2392
|
+
.__crossx-wallet-created-wallet {
|
|
2393
|
+
position: absolute;
|
|
2394
|
+
left: 55px;
|
|
2395
|
+
top: 58px;
|
|
2396
|
+
width: 94px;
|
|
2397
|
+
height: 64px;
|
|
2398
|
+
border-radius: 13px;
|
|
2399
|
+
background: #6D4CFF;
|
|
2400
|
+
}
|
|
2401
|
+
.__crossx-wallet-created-wallet::before {
|
|
2402
|
+
content: '';
|
|
2403
|
+
position: absolute;
|
|
2404
|
+
left: 11px;
|
|
2405
|
+
top: 12px;
|
|
2406
|
+
width: 72px;
|
|
2407
|
+
height: 15px;
|
|
2408
|
+
border-radius: 4px;
|
|
2409
|
+
background: #00CEB2;
|
|
2410
|
+
}
|
|
2411
|
+
.__crossx-wallet-created-wallet::after {
|
|
2412
|
+
content: '';
|
|
2413
|
+
position: absolute;
|
|
2414
|
+
left: 11px;
|
|
2415
|
+
top: 30px;
|
|
2416
|
+
width: 72px;
|
|
2417
|
+
height: 12px;
|
|
2418
|
+
border-radius: 3px;
|
|
2419
|
+
background: #FFFFFF;
|
|
2420
|
+
}
|
|
2421
|
+
.__crossx-wallet-created-coin {
|
|
2422
|
+
position: absolute;
|
|
2423
|
+
left: 52px;
|
|
2424
|
+
top: 74px;
|
|
2425
|
+
width: 30px;
|
|
2426
|
+
height: 30px;
|
|
2427
|
+
border-radius: 50%;
|
|
2428
|
+
background: #00CEB2;
|
|
2429
|
+
}
|
|
2430
|
+
.__crossx-wallet-created-coin::before,
|
|
2431
|
+
.__crossx-wallet-created-coin::after {
|
|
2432
|
+
content: '';
|
|
2433
|
+
position: absolute;
|
|
2434
|
+
height: 3px;
|
|
2435
|
+
border-radius: 9999px;
|
|
2436
|
+
background: #FFFFFF;
|
|
2437
|
+
transform: rotate(-28deg);
|
|
2438
|
+
}
|
|
2439
|
+
.__crossx-wallet-created-coin::before {
|
|
2440
|
+
left: 6px;
|
|
2441
|
+
top: 13px;
|
|
2442
|
+
width: 18px;
|
|
2443
|
+
}
|
|
2444
|
+
.__crossx-wallet-created-coin::after {
|
|
2445
|
+
left: 10px;
|
|
2446
|
+
top: 18px;
|
|
2447
|
+
width: 14px;
|
|
2448
|
+
}
|
|
2449
|
+
.__crossx-wallet-created-burst {
|
|
2450
|
+
position: absolute;
|
|
2451
|
+
left: 124px;
|
|
2452
|
+
top: 30px;
|
|
2453
|
+
width: 30px;
|
|
2454
|
+
height: 30px;
|
|
2455
|
+
border-radius: 50%;
|
|
2456
|
+
background: #FF5D85;
|
|
2457
|
+
}
|
|
2458
|
+
.__crossx-wallet-created-burst::before,
|
|
2459
|
+
.__crossx-wallet-created-burst::after {
|
|
2460
|
+
content: '';
|
|
2461
|
+
position: absolute;
|
|
2462
|
+
left: 7px;
|
|
2463
|
+
top: 13px;
|
|
2464
|
+
width: 16px;
|
|
2465
|
+
height: 3px;
|
|
2466
|
+
border-radius: 9999px;
|
|
2467
|
+
background: #FFFFFF;
|
|
2468
|
+
}
|
|
2469
|
+
.__crossx-wallet-created-burst::after {
|
|
2470
|
+
transform: rotate(90deg);
|
|
2471
|
+
}
|
|
2472
|
+
.__crossx-wallet-created-pointer {
|
|
2473
|
+
position: absolute;
|
|
2474
|
+
left: 147px;
|
|
2475
|
+
top: 90px;
|
|
2476
|
+
width: 28px;
|
|
2477
|
+
height: 28px;
|
|
2478
|
+
border-radius: 50%;
|
|
2479
|
+
background: #FFFFFF;
|
|
2480
|
+
border: 2px solid rgba(0,0,0,0.18);
|
|
2481
|
+
}
|
|
2482
|
+
.__crossx-wallet-created-pointer::before {
|
|
2483
|
+
content: '';
|
|
2484
|
+
position: absolute;
|
|
2485
|
+
left: 8px;
|
|
2486
|
+
top: 7px;
|
|
2487
|
+
width: 12px;
|
|
2488
|
+
height: 12px;
|
|
2489
|
+
background: #252B39;
|
|
2490
|
+
clip-path: polygon(0 36%, 100% 0, 62% 100%, 43% 62%);
|
|
2491
|
+
}
|
|
2492
|
+
.__crossx-wallet-created-sparkle {
|
|
2493
|
+
position: absolute;
|
|
2494
|
+
width: 14px;
|
|
2495
|
+
height: 14px;
|
|
2496
|
+
}
|
|
2497
|
+
.__crossx-wallet-created-sparkle::before,
|
|
2498
|
+
.__crossx-wallet-created-sparkle::after {
|
|
2499
|
+
content: '';
|
|
2500
|
+
position: absolute;
|
|
2501
|
+
border-radius: 9999px;
|
|
2502
|
+
background: currentColor;
|
|
2503
|
+
}
|
|
2504
|
+
.__crossx-wallet-created-sparkle::before {
|
|
2505
|
+
left: 6px;
|
|
2506
|
+
top: 0;
|
|
2507
|
+
width: 3px;
|
|
2508
|
+
height: 14px;
|
|
2509
|
+
}
|
|
2510
|
+
.__crossx-wallet-created-sparkle::after {
|
|
2511
|
+
left: 0;
|
|
2512
|
+
top: 6px;
|
|
2513
|
+
width: 14px;
|
|
2514
|
+
height: 3px;
|
|
2515
|
+
}
|
|
2516
|
+
.__crossx-wallet-created-sparkle--purple {
|
|
2517
|
+
left: 126px;
|
|
2518
|
+
top: 22px;
|
|
2519
|
+
color: #8D79FF;
|
|
2520
|
+
transform: rotate(26deg);
|
|
2521
|
+
}
|
|
2522
|
+
.__crossx-wallet-created-sparkle--teal {
|
|
2523
|
+
left: 32px;
|
|
2524
|
+
top: 108px;
|
|
2525
|
+
color: #00CEB2;
|
|
2526
|
+
}
|
|
2527
|
+
.__crossx-wallet-created-dot {
|
|
2528
|
+
position: absolute;
|
|
2529
|
+
width: 6px;
|
|
2530
|
+
height: 6px;
|
|
2531
|
+
border-radius: 50%;
|
|
2532
|
+
background: #BFD0EA;
|
|
2533
|
+
}
|
|
2534
|
+
.__crossx-wallet-created-dot--one {
|
|
2535
|
+
left: 122px;
|
|
2536
|
+
top: 34px;
|
|
2537
|
+
}
|
|
2538
|
+
.__crossx-wallet-created-dot--two {
|
|
2539
|
+
left: 178px;
|
|
2540
|
+
top: 87px;
|
|
2541
|
+
}
|
|
2542
|
+
.__crossx-wallet-created-footer {
|
|
2543
|
+
padding: 12px 24px 24px;
|
|
2544
|
+
width: 100%;
|
|
2545
|
+
box-sizing: border-box;
|
|
2546
|
+
}
|
|
2547
|
+
.__crossx-wallet-created-btn {
|
|
2548
|
+
width: 100%;
|
|
2549
|
+
height: 48px;
|
|
2550
|
+
border: none;
|
|
2551
|
+
border-radius: 12px;
|
|
2552
|
+
background: var(--cx-primary);
|
|
2553
|
+
color: var(--cx-on-primary);
|
|
2554
|
+
font-family: inherit;
|
|
2555
|
+
font-size: 16px;
|
|
2556
|
+
font-weight: 600;
|
|
2557
|
+
line-height: 1.5;
|
|
2558
|
+
letter-spacing: -0.01em;
|
|
2559
|
+
cursor: pointer;
|
|
2560
|
+
}
|
|
2561
|
+
.__crossx-wallet-created-btn:hover,
|
|
2562
|
+
.__crossx-wallet-created-btn:focus,
|
|
2563
|
+
.__crossx-wallet-created-btn:active {
|
|
2564
|
+
opacity: 1 !important;
|
|
2565
|
+
box-shadow: none !important;
|
|
2566
|
+
outline: none !important;
|
|
2567
|
+
filter: none !important;
|
|
2568
|
+
transform: none !important;
|
|
2569
|
+
background: var(--cx-primary) !important;
|
|
2570
|
+
color: var(--cx-on-primary) !important;
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2117
2573
|
/* ── Amount tooltip ──────────────────────────────────────────────── */
|
|
2118
2574
|
.__crossx-amount-tip {
|
|
2119
2575
|
cursor: default;
|
|
@@ -2136,27 +2592,27 @@ button.__crossx-connect-other-block:active {
|
|
|
2136
2592
|
.__crossx-tip-overlay.--visible {
|
|
2137
2593
|
display: block;
|
|
2138
2594
|
}
|
|
2139
|
-
`;function ae(){let s=document.getElementById(ur);s||(s=document.createElement("style"),s.id=ur,document.head.appendChild(s)),s.textContent=
|
|
2595
|
+
`;function ae(){let s=document.getElementById(ur);s||(s=document.createElement("style"),s.id=ur,document.head.appendChild(s)),s.textContent=pi}function _i(){const s=`#${Q}`,e=t=>{var n,i;(i=(n=t.target)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()},r=t=>{var n,i;(i=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function ce(s){const e=s.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const c=a[1].trim();s.style.setProperty("--cx-bg",c);const l=document.createElement("div");l.className="__crossx-safe-area-fill",l.style.background=c,s.appendChild(l)}}const r=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(o,r);s.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])s.addEventListener(o,r);s.addEventListener("touchmove",o=>{o.stopPropagation();let a=o.target;for(;a&&a!==s;){const c=window.getComputedStyle(a);if((c.overflowY==="auto"||c.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}o.preventDefault()},{passive:!1});const t=_i(),n=fi(s),i=s.remove.bind(s);s.remove=()=>{n(),t(),i()},document.body.appendChild(s)}function fi(s){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const n=window.innerHeight,i=e.offsetTop+e.height,o=Math.max(0,Math.round(n-i));o!==r&&(r=o,s.style.setProperty("--cx-keyboard-inset",`${o}px`))};return t(),e.addEventListener("resize",t),e.addEventListener("scroll",t),()=>{e.removeEventListener("resize",t),e.removeEventListener("scroll",t),s.style.removeProperty("--cx-keyboard-inset")}}function xi(s){const e=Array.from(s.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",s.appendChild(r);let t=null;const n=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const c=o.getBoundingClientRect(),l=r.offsetWidth,u=r.offsetHeight;let p=c.right-l,x=c.top-u-6;p<8&&(p=8),x<8&&(x=c.bottom+6),r.style.left=`${p}px`,r.style.top=`${x}px`,t=o},i=()=>{r.classList.remove("--visible"),t=null};e.forEach(o=>{o.addEventListener("mouseenter",()=>n(o)),o.addEventListener("mouseleave",i),o.addEventListener("touchstart",a=>{a.stopPropagation(),t===o?i():n(o)},{passive:!0})}),s.addEventListener("touchstart",o=>{o.target.closest(".__crossx-amount-tip")||i()},{passive:!0})}const gi=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Ie(){if(gi()){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 s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function me(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function Jr(s){return s?s.length<=13?s:`${s.slice(0,6)}...${s.slice(-4)}`:"—"}function Zr(s,e="CROSS",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=At(n,r,t);if(i==="0")return null;const o=St(n,r);return Et(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const pr={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Qr(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&pr[e]?pr[e]:s}function St(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,i=(s%r).toString().padStart(e,"0").replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function Et(s,e){return s===e?S(s):`<span class="__crossx-amount-tip" data-full="${S(e)}">${S(s)}</span>`}function At(s,e,r){if(s===0n)return"0";const t=10n**BigInt(e),n=s/t,a=(s%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${n}.${a}`:`${n}`}function xt(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function wi(s){try{return BigInt(s).toLocaleString()}catch{return s}}function mi(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeSymbol:o="ETH",nativeDecimals:a=18}=s;if(!r)return null;try{const c=BigInt(r),l=wi(r);if(n){const u=c*BigInt(n);return{isDynamic:!0,estTxFee:Et(`${At(u,a,e)} ${o}`,`${St(u,a)} ${o}`),maxFeeGwei:xt(n),maxPriorityFeeGwei:i?xt(i):void 0,gasLimitFormatted:l}}if(t){const u=c*BigInt(t);return{isDynamic:!1,estTxFee:Et(`${At(u,a,e)} ${o}`,`${St(u,a)} ${o}`),gasPriceGwei:xt(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function es(s,e,r){const t=mi(s,e);if(!t)return Z((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=Z((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=Z((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=Z((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=Z((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=Z((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),n}const ge=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2140
2596
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
2141
2597
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
2142
2598
|
</svg>`,ne=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
2143
2599
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
2144
2600
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
2145
|
-
</svg>`,
|
|
2601
|
+
</svg>`,yi=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2146
2602
|
<circle cx="20" cy="20" r="20" fill="#00D5AA"/>
|
|
2147
2603
|
<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"/>
|
|
2148
|
-
</svg>`,
|
|
2604
|
+
</svg>`,bi='<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>',vi='<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>',Si='<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>',Ei={[Le.MetaMask]:bi,[Le.Binance]:vi,[Le.CROSSx]:Si},ts='<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"/>',Bt=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${ts}</svg>`,Ai=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
2149
2605
|
<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)"/>
|
|
2150
|
-
</svg>`,
|
|
2606
|
+
</svg>`,Ii=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
2151
2607
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
2152
2608
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
2153
2609
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
2154
|
-
</svg>`;function ie(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function Z(s,e){return`
|
|
2610
|
+
</svg>`;function ie(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-border-medium:${s.borderMedium}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-surface-high:${s.surfaceHigh}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-notice-bg:${s.noticeBg}`,`--cx-notice-border:${s.noticeBorder}`,`--cx-notice-title:${s.noticeTitleColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function ki(s,e){s.style.setProperty("--cx-bg",e.bg),s.style.setProperty("--cx-border",e.border),s.style.setProperty("--cx-border-medium",e.borderMedium),s.style.setProperty("--cx-title",e.titleColor),s.style.setProperty("--cx-subtitle",e.subtitleColor),s.style.setProperty("--cx-label",e.labelColor),s.style.setProperty("--cx-value",e.valueColor),s.style.setProperty("--cx-pill-bg",e.pillBg),s.style.setProperty("--cx-pill-from",e.pillFromColor),s.style.setProperty("--cx-pill-amt",e.pillAmtColor),s.style.setProperty("--cx-divider",e.divider),s.style.setProperty("--cx-close",e.closeColor),s.style.setProperty("--cx-close-hover",e.closeHoverBg),s.style.setProperty("--cx-copy",e.copyColor),s.style.setProperty("--cx-input-bg",e.inputBg),s.style.setProperty("--cx-input-border",e.inputBorder),s.style.setProperty("--cx-hint",e.hintColor),s.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),s.style.setProperty("--cx-surface-high",e.surfaceHigh),s.style.setProperty("--cx-primary",e.primary),s.style.setProperty("--cx-primary-glow",e.primaryGlow),s.style.setProperty("--cx-secondary",e.secondary),s.style.setProperty("--cx-error",e.errorColor),s.style.setProperty("--cx-notice-bg",e.noticeBg),s.style.setProperty("--cx-notice-border",e.noticeBorder),s.style.setProperty("--cx-notice-title",e.noticeTitleColor),s.style.setProperty("--cx-on-primary",e.onPrimary)}function Z(s,e){return`
|
|
2155
2611
|
<div class="__crossx-row">
|
|
2156
2612
|
<span class="__crossx-row-label">${s}</span>
|
|
2157
2613
|
<div class="__crossx-row-value">${e}</div>
|
|
2158
|
-
</div>`}function
|
|
2159
|
-
<button class="__crossx-copy-btn" data-copy="${S(s.to)}" title="Copy address">${
|
|
2614
|
+
</div>`}function Ti(s,e,r,t){const n=e,i=s.nativeSymbol??"ETH",o=s.nativeDecimals??18,a=ot(s.dappName),c=s.to?`<span class="__crossx-addr-text">${me(s.to)}</span>
|
|
2615
|
+
<button class="__crossx-copy-btn" data-copy="${S(s.to)}" title="Copy address">${ge}</button>`:"<span>—</span>",l=es(s,r,t),u=Zr(s.value,i,o,r),p=u?Z((t==null?void 0:t.label_value)??"Value",`<span>${u}</span>`):"",x=s.data??"0x",_=document.createElement("div");return _.id=Q,_.innerHTML=`
|
|
2160
2616
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ie(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2161
2617
|
<div class="__crossx-header">
|
|
2162
2618
|
<p class="__crossx-title" id="__crossx-ttl">${S((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
|
|
@@ -2170,8 +2626,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2170
2626
|
<span class="__crossx-sig-origin">${S(a)}</span>${S((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
|
|
2171
2627
|
</p>
|
|
2172
2628
|
<div class="__crossx-addr-pill">
|
|
2173
|
-
${
|
|
2174
|
-
<span class="__crossx-addr-pill-text">${
|
|
2629
|
+
${Bt}
|
|
2630
|
+
<span class="__crossx-addr-pill-text">${me(s.from)}</span>
|
|
2175
2631
|
</div>
|
|
2176
2632
|
<p class="__crossx-warning">${S((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
|
|
2177
2633
|
</div>
|
|
@@ -2179,11 +2635,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2179
2635
|
<div class="__crossx-col-right-sign">
|
|
2180
2636
|
<div class="__crossx-rows">
|
|
2181
2637
|
${Z((t==null?void 0:t.label_to)??"To",c)}
|
|
2182
|
-
${Z((t==null?void 0:t.label_network)??"Network",`<span>${
|
|
2638
|
+
${Z((t==null?void 0:t.label_network)??"Network",`<span>${Qr(s.chainId)}</span>`)}
|
|
2183
2639
|
${p}
|
|
2184
2640
|
${l}
|
|
2185
2641
|
</div>
|
|
2186
|
-
<pre class="__crossx-raw-tx">${S(
|
|
2642
|
+
<pre class="__crossx-raw-tx">${S(x)}</pre>
|
|
2187
2643
|
</div>
|
|
2188
2644
|
</div>
|
|
2189
2645
|
<div class="__crossx-btn-row">
|
|
@@ -2192,8 +2648,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2192
2648
|
</div>
|
|
2193
2649
|
</div>
|
|
2194
2650
|
</div>
|
|
2195
|
-
`,_}function
|
|
2196
|
-
<button class="__crossx-copy-btn" data-copy="${S(s.to)}" title="Copy address">${
|
|
2651
|
+
`,_}const Ri=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Ci(s){return s?Ri.has(s.slice(0,10).toLowerCase()):!1}function Ni(s,e,r,t){const n=e,i=s.nativeSymbol??"ETH",o=s.nativeDecimals??18,a=ot(s.dappName),c=s.to?`<span class="__crossx-addr-text">${me(s.to)}</span>
|
|
2652
|
+
<button class="__crossx-copy-btn" data-copy="${S(s.to)}" title="Copy address">${ge}</button>`:"<span>—</span>",l=es(s,r,t),p=Zr(s.value,i,o,r)??"—",x=Ci(s.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",_=document.createElement("div");return _.id=Q,_.innerHTML=`
|
|
2197
2653
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ie(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2198
2654
|
<div class="__crossx-header">
|
|
2199
2655
|
<p class="__crossx-title" id="__crossx-ttl">${S((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
|
|
@@ -2207,24 +2663,24 @@ button.__crossx-connect-other-block:active {
|
|
|
2207
2663
|
<div class="__crossx-body-cols">
|
|
2208
2664
|
<div class="__crossx-rows">
|
|
2209
2665
|
${Z((t==null?void 0:t.label_to)??"To",c)}
|
|
2210
|
-
${Z((t==null?void 0:t.label_network)??"Network",`<span>${
|
|
2666
|
+
${Z((t==null?void 0:t.label_network)??"Network",`<span>${Qr(s.chainId)}</span>`)}
|
|
2211
2667
|
${l}
|
|
2212
2668
|
</div>
|
|
2213
2669
|
<div class="__crossx-pill">
|
|
2214
|
-
<span class="__crossx-pill-from">${
|
|
2670
|
+
<span class="__crossx-pill-from">${me(s.from)}</span>
|
|
2215
2671
|
<span class="__crossx-pill-amount">${p}</span>
|
|
2216
2672
|
</div>
|
|
2217
2673
|
</div>
|
|
2218
|
-
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">${S(
|
|
2674
|
+
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">${S(x)}</button>
|
|
2219
2675
|
</div>
|
|
2220
2676
|
</div>
|
|
2221
|
-
`,
|
|
2222
|
-
<button class="__crossx-copy-btn" data-copy="${S(s.from)}" title="Copy address">${
|
|
2223
|
-
<button class="__crossx-copy-btn" data-copy="${S(s.to)}" title="Copy address">${
|
|
2224
|
-
<button class="__crossx-copy-btn" data-copy="${S(s.txHash)}" title="Copy hash">${
|
|
2677
|
+
`,_}function ot(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function S(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Pi(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function Oi(s){if(typeof s=="string")return S(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return S(JSON.stringify(s))}catch{return String(s)}}function Li(s){return s.includes(":")?s.split(":")[1]??s:s}function Di(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function Bi(s,e){return`https://explorer.crosstoken.io/${Li(s)}/tx/${e}`}function rs(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${S(e)}" target="_blank" rel="noopener noreferrer">${S(s)}</a>`}function tt(s){return rs(me(s),Di(s))}function ss(s,e){return rs(me(e),Bi(s,e))}function $i(s,e,r){const t=Z((r==null?void 0:r.label_from)??"From",`${tt(s.from)}
|
|
2678
|
+
<button class="__crossx-copy-btn" data-copy="${S(s.from)}" title="Copy address">${ge}</button>`),n=s.to?Z((r==null?void 0:r.label_to)??"To",`${tt(s.to)}
|
|
2679
|
+
<button class="__crossx-copy-btn" data-copy="${S(s.to)}" title="Copy address">${ge}</button>`):"",i=s.amount?Z((r==null?void 0:r.label_transfer)??"Transfer",`<span>${S(s.amount)}</span>`):"",o=s.fees?Z((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${S(s.fees)}</span>`):"",a=s.txHash?Z((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${ss(s.chainId,s.txHash)}
|
|
2680
|
+
<button class="__crossx-copy-btn" data-copy="${S(s.txHash)}" title="Copy hash">${ge}</button>`):"",c=s.total?`<div class="__crossx-total-pill">
|
|
2225
2681
|
<span class="__crossx-total-label">${S((r==null?void 0:r.label_total)??"Total")}<br>${S((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
|
|
2226
2682
|
<span class="__crossx-total-amount">${S(s.total)}</span>
|
|
2227
|
-
</div>`:"",l=document.createElement("div");return l.id=
|
|
2683
|
+
</div>`:"",l=document.createElement("div");return l.id=Q,l.innerHTML=`
|
|
2228
2684
|
<div class="__crossx-card __crossx-card--migration" style="${ie(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2229
2685
|
<div class="__crossx-header">
|
|
2230
2686
|
<p class="__crossx-title" id="__crossx-ttl">${S((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
|
|
@@ -2243,7 +2699,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2243
2699
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${S((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
|
|
2244
2700
|
</div>
|
|
2245
2701
|
</div>
|
|
2246
|
-
`,l}function
|
|
2702
|
+
`,l}function Mi(s,e,r){const t=document.createElement("div");return t.id=Q,t.innerHTML=`
|
|
2247
2703
|
<div class="__crossx-card __crossx-card--migration" style="${ie(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2248
2704
|
<div class="__crossx-header">
|
|
2249
2705
|
<p class="__crossx-title" id="__crossx-ttl">${S((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
|
|
@@ -2256,10 +2712,10 @@ button.__crossx-connect-other-block:active {
|
|
|
2256
2712
|
</div>
|
|
2257
2713
|
</div>
|
|
2258
2714
|
</div>
|
|
2259
|
-
`,t}function
|
|
2260
|
-
<button class="__crossx-copy-btn" data-copy="${S(e.from)}" title="Copy address">${
|
|
2261
|
-
<button class="__crossx-copy-btn" data-copy="${S(e.to)}" title="Copy address">${
|
|
2262
|
-
<button class="__crossx-copy-btn" data-copy="${S(e.txHash)}" title="Copy hash">${
|
|
2715
|
+
`,t}function Fi(s,e,r,t){const n=e.status!=="reverted"&&e.status!=="timeout",i=e.status==="timeout",o=s.querySelector("#__crossx-ttl"),a=s.querySelector(".__crossx-header");if(o){const w=i?Ii:n?"":Ai,b=i?(t==null?void 0:t.tx_timeout)??"Transaction timeout":n?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${S(b)}</span>`):o.textContent=b}if(a&&!s.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ne,a.appendChild(w)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?Z((t==null?void 0:t.label_from)??"From",`${tt(e.from)}
|
|
2716
|
+
<button class="__crossx-copy-btn" data-copy="${S(e.from)}" title="Copy address">${ge}</button>`):"",u=e.to?Z((t==null?void 0:t.label_to)??"To",`${tt(e.to)}
|
|
2717
|
+
<button class="__crossx-copy-btn" data-copy="${S(e.to)}" title="Copy address">${ge}</button>`):"",p=e.amount?Z((t==null?void 0:t.label_transfer)??"Transfer",`<span>${S(e.amount)}</span>`):"",x=e.fees?Z((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${S(e.fees)}</span>`):"",_=e.txHash?Z((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${ss(e.chainId,e.txHash)}
|
|
2718
|
+
<button class="__crossx-copy-btn" data-copy="${S(e.txHash)}" title="Copy hash">${ge}</button>`):"",g=e.total?`<div class="__crossx-total-pill">
|
|
2263
2719
|
<span class="__crossx-total-label">${S((t==null?void 0:t.label_total)??"Total")}<br>${S((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
|
|
2264
2720
|
<span class="__crossx-total-amount">${S(e.total)}</span>
|
|
2265
2721
|
</div>`:"";c.innerHTML=`
|
|
@@ -2267,12 +2723,12 @@ button.__crossx-connect-other-block:active {
|
|
|
2267
2723
|
${l}
|
|
2268
2724
|
${u}
|
|
2269
2725
|
${p}
|
|
2270
|
-
${
|
|
2726
|
+
${x}
|
|
2271
2727
|
${_}
|
|
2272
2728
|
</div>
|
|
2273
|
-
${
|
|
2729
|
+
${g}
|
|
2274
2730
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${S((t==null?void 0:t.tx_complete_done_button)??(n?"All Done":"Done"))}</button>
|
|
2275
|
-
`,c.querySelectorAll(".__crossx-copy-btn").forEach(
|
|
2731
|
+
`,c.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",b=>{var T;b.stopPropagation();const A=w.dataset.copy;A&&((T=navigator.clipboard)==null||T.writeText(A).catch(()=>{}))})})}function Ui(s,e,r){const t=e,n=ot(s.dappName),i=S(s.message),o=document.createElement("div");return o.id=Q,o.innerHTML=`
|
|
2276
2732
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ie(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2277
2733
|
<div class="__crossx-header">
|
|
2278
2734
|
<p class="__crossx-title" id="__crossx-ttl">${S((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
|
|
@@ -2286,8 +2742,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2286
2742
|
<span class="__crossx-sig-origin">${S(n)}</span>${S((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
|
|
2287
2743
|
</p>
|
|
2288
2744
|
<div class="__crossx-addr-pill">
|
|
2289
|
-
${
|
|
2290
|
-
<span class="__crossx-addr-pill-text">${
|
|
2745
|
+
${Bt}
|
|
2746
|
+
<span class="__crossx-addr-pill-text">${me(s.from)}</span>
|
|
2291
2747
|
</div>
|
|
2292
2748
|
<p class="__crossx-warning">${S((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
|
|
2293
2749
|
</div>
|
|
@@ -2300,16 +2756,16 @@ button.__crossx-connect-other-block:active {
|
|
|
2300
2756
|
</div>
|
|
2301
2757
|
</div>
|
|
2302
2758
|
</div>
|
|
2303
|
-
`,o}function
|
|
2759
|
+
`,o}function Hi(s,e,r){const t=e,n=ot(s.dappName);let i={};if(typeof s.typedData=="string")try{i=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(i=s.typedData);const o=i.primaryType??"—",a=i.message??{};let c=`
|
|
2304
2760
|
<div class="__crossx-td-row">
|
|
2305
2761
|
<span class="__crossx-td-label">${S((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
|
|
2306
2762
|
<span class="__crossx-td-value">${S(o)}</span>
|
|
2307
|
-
</div>`;for(const[u,p]of Object.entries(a)){const
|
|
2308
|
-
<button class="__crossx-copy-btn" data-copy="${S(String(p))}" title="Copy">${
|
|
2763
|
+
</div>`;for(const[u,p]of Object.entries(a)){const x=Oi(p),g=Pi(p)?`<span class="__crossx-addr-text">${me(p)}</span>
|
|
2764
|
+
<button class="__crossx-copy-btn" data-copy="${S(String(p))}" title="Copy">${ge}</button>`:`<span>${x}</span>`;c+=`
|
|
2309
2765
|
<div class="__crossx-td-row">
|
|
2310
2766
|
<span class="__crossx-td-label">${S(u)}</span>
|
|
2311
|
-
<div class="__crossx-td-value">${
|
|
2312
|
-
</div>`}const l=document.createElement("div");return l.id=
|
|
2767
|
+
<div class="__crossx-td-value">${g}</div>
|
|
2768
|
+
</div>`}const l=document.createElement("div");return l.id=Q,l.innerHTML=`
|
|
2313
2769
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ie(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2314
2770
|
<div class="__crossx-header">
|
|
2315
2771
|
<p class="__crossx-title" id="__crossx-ttl">${S((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
|
|
@@ -2323,8 +2779,8 @@ button.__crossx-connect-other-block:active {
|
|
|
2323
2779
|
<span class="__crossx-sig-origin">${S(n)}</span>${S((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
|
|
2324
2780
|
</p>
|
|
2325
2781
|
<div class="__crossx-addr-pill">
|
|
2326
|
-
${
|
|
2327
|
-
<span class="__crossx-addr-pill-text">${
|
|
2782
|
+
${Bt}
|
|
2783
|
+
<span class="__crossx-addr-pill-text">${me(s.from)}</span>
|
|
2328
2784
|
</div>
|
|
2329
2785
|
<p class="__crossx-warning">${S((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
|
|
2330
2786
|
</div>
|
|
@@ -2337,61 +2793,59 @@ button.__crossx-connect-other-block:active {
|
|
|
2337
2793
|
</div>
|
|
2338
2794
|
</div>
|
|
2339
2795
|
</div>
|
|
2340
|
-
`,l}const
|
|
2796
|
+
`,l}const Wi=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2341
2797
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2342
2798
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2343
|
-
</svg>`,
|
|
2344
|
-
${
|
|
2345
|
-
</button>`}).join(""),o=document.createElement("div");return o.id=
|
|
2346
|
-
<div class="__crossx-card __crossx-card--
|
|
2799
|
+
</svg>`,Gi='<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 ns(s){return s.name||`Account ${s.index+1}`}function qi(){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">${ts}</g></svg>`}const Ki=mr().portraitBaseUrl;function Vi(s,e){const r=e.replace("#","");return`${Ki}/portrait/evm/${s}.png?size=256&bg=${r}`}function is(s,e,r){const t=Vi(s,r),i=qi().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='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function zi(s,e,r,t){const n=r==null?void 0:r.toLowerCase(),i=s.map(a=>{const c=n&&a.address.toLowerCase()===n,l=c?" __crossx-wallet-item--selected":"",u=c?`<span class="__crossx-wallet-selected">${S((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${Gi}</span>`:"";return`<button class="__crossx-wallet-item${l}" data-wallet-index="${a.index}" data-wallet-address="${S(a.address)}">
|
|
2800
|
+
${is(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${S(ns(a))}</span><span class="__crossx-wallet-addr">${Jr(a.address)}</span></span>${u}
|
|
2801
|
+
</button>`}).join(""),o=document.createElement("div");return o.id=Q,o.className="__crossx-overlay--wallet-selector",o.innerHTML=`
|
|
2802
|
+
<div class="__crossx-card __crossx-card--wallet-selector" style="${ie(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2347
2803
|
<div class="__crossx-header">
|
|
2348
|
-
<
|
|
2349
|
-
|
|
2804
|
+
<span class="__crossx-wallet-sheet-handle" aria-hidden="true"></span>
|
|
2805
|
+
<div class="__crossx-wallet-header-copy">
|
|
2806
|
+
<p class="__crossx-title" id="__crossx-ttl">${S((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
|
|
2350
2807
|
<p class="__crossx-subtitle--body">${S((t==null?void 0:t.wallet_selector_description)??"Please select the wallet you previously used for this game to continue.")}</p>
|
|
2351
2808
|
</div>
|
|
2352
2809
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
|
|
2353
2810
|
</div>
|
|
2354
2811
|
<hr class="__crossx-divider">
|
|
2355
|
-
<div class="__crossx-body">
|
|
2356
|
-
<div class="__crossx-
|
|
2357
|
-
<div class="__crossx-
|
|
2358
|
-
|
|
2359
|
-
<p class="__crossx-mig-info-title">${S((t==null?void 0:t.wallet_selector_info_title)??"Why do I need to select a wallet?")}</p>
|
|
2360
|
-
<p class="__crossx-mig-info-desc">${S((t==null?void 0:t.wallet_selector_info_desc)??"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.")}</p>
|
|
2361
|
-
</div>
|
|
2812
|
+
<div class="__crossx-body __crossx-wallet-selector-body">
|
|
2813
|
+
<div class="__crossx-wallet-list-section">
|
|
2814
|
+
<div class="__crossx-wallet-list" id="__crossx-wallet-list">
|
|
2815
|
+
${i}
|
|
2362
2816
|
</div>
|
|
2363
|
-
<
|
|
2364
|
-
|
|
2365
|
-
<
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
</
|
|
2372
|
-
<p class="__crossx-
|
|
2817
|
+
<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
|
|
2818
|
+
<span class="__crossx-wallet-add-icon">${Wi}</span>
|
|
2819
|
+
<span class="__crossx-wallet-add-label">${S((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
|
|
2820
|
+
</button>
|
|
2821
|
+
<p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
|
|
2822
|
+
</div>
|
|
2823
|
+
<div class="__crossx-wallet-help-section">
|
|
2824
|
+
<div class="__crossx-mig-info">
|
|
2825
|
+
<p class="__crossx-mig-info-title">${S((t==null?void 0:t.wallet_selector_info_title)??"Why do I need to select a wallet?")}</p>
|
|
2826
|
+
<p class="__crossx-mig-info-desc">${S((t==null?void 0:t.wallet_selector_info_desc)??"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.")}</p>
|
|
2373
2827
|
</div>
|
|
2374
2828
|
</div>
|
|
2375
2829
|
</div>
|
|
2376
2830
|
</div>
|
|
2377
|
-
`,o}const
|
|
2831
|
+
`,o}function ji(s,e){const r=document.createElement("div");r.id=Q;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",ki(t,s),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const n=document.createElement("div");n.className="__crossx-header";const i=document.createElement("span");i.className="__crossx-wallet-created-sheet-handle",i.ariaHidden="true";const o=document.createElement("p");o.className="__crossx-title",o.id="__crossx-ttl",o.style.paddingRight="48px",o.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.textContent="×",n.append(i,o,a);const c=document.createElement("hr");c.className="__crossx-divider";const l=document.createElement("div");l.className="__crossx-wallet-created-body";const u=document.createElement("div");u.className="__crossx-wallet-created-hero";const p=document.createElement("span");p.className="__crossx-wallet-created-illust",p.ariaHidden="true";const x=w=>{const b=document.createElement("span");return b.className=w,b};p.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")),u.appendChild(p),l.appendChild(u);const _=document.createElement("div");_.className="__crossx-wallet-created-footer";const g=document.createElement("button");return g.className="__crossx-wallet-created-btn",g.id="__crossx-wallet-created-done",g.type="button",g.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",_.appendChild(g),t.append(n,c,l,_),r.appendChild(t),r}const Yi=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2378
2832
|
<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"/>
|
|
2379
2833
|
<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"/>
|
|
2380
|
-
</svg>`,
|
|
2834
|
+
</svg>`,Xi=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2381
2835
|
<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"/>
|
|
2382
2836
|
<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"/>
|
|
2383
2837
|
<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"/>
|
|
2384
2838
|
<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"/>
|
|
2385
|
-
</svg>`;function
|
|
2839
|
+
</svg>`;function Ji(s){const e=xr(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Ei[s]??""}</span><span class="__crossx-connect-other-wallet-name">${S(e)}</span></span>`}function Zi(s){if(s.length===0)return"";const e=n=>Ji(s[n]),r="Supported wallets include ";if(s.length===1)return`${r}${e(0)}.`;if(s.length===2)return`${r}${e(0)} and ${e(1)}.`;if(s.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=s.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function Qi(s,e=[],r){const t=s,n=S(String(e[0])),i=S((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
|
|
2386
2840
|
<div class="__crossx-login-or-divider">
|
|
2387
2841
|
<hr><span>${i}</span><hr>
|
|
2388
2842
|
</div>
|
|
2389
2843
|
<button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${n}" aria-labelledby="__crossx-connect-other-heading">
|
|
2390
2844
|
<span class="__crossx-connect-other-text">
|
|
2391
2845
|
<span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${S((r==null?void 0:r.login_selector_connect_other_wallets)??"Connect with Other Wallets")}</span>
|
|
2392
|
-
<span class="__crossx-connect-other-desc __crossx-connect-other-summary">${
|
|
2846
|
+
<span class="__crossx-connect-other-desc __crossx-connect-other-summary">${Zi(e)}</span>
|
|
2393
2847
|
</span>
|
|
2394
|
-
</button>`:"",a=document.createElement("div");return a.id=
|
|
2848
|
+
</button>`:"",a=document.createElement("div");return a.id=Q,a.innerHTML=`
|
|
2395
2849
|
<div class="__crossx-card __crossx-card--migration" style="${ie(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2396
2850
|
<div class="__crossx-header">
|
|
2397
2851
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -2404,11 +2858,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2404
2858
|
<div class="__crossx-body">
|
|
2405
2859
|
<div class="__crossx-login-btn-row">
|
|
2406
2860
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
2407
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
2861
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${Yi}</span>
|
|
2408
2862
|
<span class="__crossx-login-btn-label">${S((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
|
|
2409
2863
|
</button>
|
|
2410
2864
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
2411
|
-
<span class="__crossx-login-icon">${
|
|
2865
|
+
<span class="__crossx-login-icon">${Xi}</span>
|
|
2412
2866
|
<span class="__crossx-login-btn-label">${S((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
|
|
2413
2867
|
</button>
|
|
2414
2868
|
</div>${o}
|
|
@@ -2417,7 +2871,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2417
2871
|
</p>
|
|
2418
2872
|
</div>
|
|
2419
2873
|
</div>
|
|
2420
|
-
`,a}function
|
|
2874
|
+
`,a}function eo(s,e){const r=s,t=document.createElement("div");t.id=Q;const n=S(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
|
|
2421
2875
|
<p class="__crossx-session-account-label">${S(e.accountLabel)}</p>
|
|
2422
2876
|
<p class="__crossx-session-account-email">${S(e.email)}</p>
|
|
2423
2877
|
</div>`:"";return t.innerHTML=`
|
|
@@ -2439,7 +2893,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2439
2893
|
</div>
|
|
2440
2894
|
</div>
|
|
2441
2895
|
</div>
|
|
2442
|
-
`,t}function
|
|
2896
|
+
`,t}function to(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=Q,i.innerHTML=`
|
|
2443
2897
|
<div class="__crossx-card __crossx-card--migration" style="${ie(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2444
2898
|
<div class="__crossx-header">
|
|
2445
2899
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2453,13 +2907,13 @@ button.__crossx-connect-other-block:active {
|
|
|
2453
2907
|
<p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
|
|
2454
2908
|
</div>
|
|
2455
2909
|
<button class="__crossx-recover-btn" id="__crossx-recover-btn">
|
|
2456
|
-
<span class="__crossx-recover-icon">${
|
|
2910
|
+
<span class="__crossx-recover-icon">${yi}</span>
|
|
2457
2911
|
<span class="__crossx-recover-label">Import from Social Backup</span>
|
|
2458
2912
|
</button>
|
|
2459
2913
|
${n}
|
|
2460
2914
|
</div>
|
|
2461
2915
|
</div>
|
|
2462
|
-
`,i}function
|
|
2916
|
+
`,i}function ro(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=Q,p.innerHTML=`
|
|
2463
2917
|
<div class="__crossx-card __crossx-card--migration" style="${ie(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2464
2918
|
<div class="__crossx-header">
|
|
2465
2919
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2479,7 +2933,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2479
2933
|
${u}
|
|
2480
2934
|
</div>
|
|
2481
2935
|
</div>
|
|
2482
|
-
`,p}function
|
|
2936
|
+
`,p}function so(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function no(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?so(i):null,a=document.createElement("div");return a.id=Q,a.innerHTML=`
|
|
2483
2937
|
<div class="__crossx-card __crossx-card--migration" style="${ie(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2484
2938
|
<div class="__crossx-header">
|
|
2485
2939
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2499,13 +2953,14 @@ button.__crossx-connect-other-block:active {
|
|
|
2499
2953
|
</div>
|
|
2500
2954
|
</div>
|
|
2501
2955
|
</div>
|
|
2502
|
-
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function
|
|
2956
|
+
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function io(s){const r=[s.check1,s.check2].map((t,n)=>`
|
|
2503
2957
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2504
|
-
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${
|
|
2958
|
+
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${lo}</div>
|
|
2505
2959
|
<span class="__crossx-pw-notice-item-text">${S(t)}</span>
|
|
2506
2960
|
</div>
|
|
2507
2961
|
`).join("");return`
|
|
2508
2962
|
<div class="__crossx-header">
|
|
2963
|
+
<span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
|
|
2509
2964
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${S(s.title)}</p>
|
|
2510
2965
|
<p class="__crossx-pw-subtitle">${S(s.headerSubtitle)}</p>
|
|
2511
2966
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
|
|
@@ -2515,7 +2970,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2515
2970
|
<div class="__crossx-pw-fields __crossx-pw-fields--notice">
|
|
2516
2971
|
<div class="__crossx-pw-notice-header">
|
|
2517
2972
|
<div class="__crossx-pw-notice-title-row">
|
|
2518
|
-
<span class="__crossx-pw-notice-icon">${
|
|
2973
|
+
<span class="__crossx-pw-notice-icon">${uo}</span>
|
|
2519
2974
|
<p class="__crossx-pw-notice-title">${S(s.noticeTitle)}</p>
|
|
2520
2975
|
</div>
|
|
2521
2976
|
<p class="__crossx-pw-notice-desc">${S(s.noticeDesc)}</p>
|
|
@@ -2524,17 +2979,19 @@ button.__crossx-connect-other-block:active {
|
|
|
2524
2979
|
${r}
|
|
2525
2980
|
</div>
|
|
2526
2981
|
</div>
|
|
2982
|
+
</div>
|
|
2983
|
+
<div class="__crossx-pin6-footer">
|
|
2527
2984
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2528
2985
|
data-next-label="${S(s.nextButton)}"
|
|
2529
2986
|
data-submit-label="${S(s.submitButton)}">
|
|
2530
|
-
${S(s.
|
|
2987
|
+
${S(s.submitButton)}
|
|
2531
2988
|
</button>
|
|
2532
2989
|
</div>
|
|
2533
2990
|
<div class="__crossx-home-indicator"></div>
|
|
2534
|
-
`}function
|
|
2535
|
-
${
|
|
2991
|
+
`}function gt(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${S(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${S(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${S(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2992
|
+
${os}
|
|
2536
2993
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2537
|
-
</p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${S(s.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(
|
|
2994
|
+
</p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${S(s.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(w,b)=>`<input class="__crossx-pin6-box${l}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-label="PIN digit ${b+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",x=Array.from({length:6},(w,b)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${b}" aria-label="PIN digit ${b+1}"></div>`).join(""),_=e?" --disabled":"",g=`
|
|
2538
2995
|
<div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
|
|
2539
2996
|
<div class="__crossx-pin6-numpad-row">
|
|
2540
2997
|
<button type="button" class="__crossx-pin6-numpad-key${_}" data-key="1">1</button>
|
|
@@ -2554,10 +3011,11 @@ button.__crossx-connect-other-block:active {
|
|
|
2554
3011
|
<div class="__crossx-pin6-numpad-row">
|
|
2555
3012
|
<button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
|
|
2556
3013
|
<button type="button" class="__crossx-pin6-numpad-key${_}" data-key="0">0</button>
|
|
2557
|
-
<button type="button" class="__crossx-pin6-numpad-key --delete${_}" data-key="backspace" aria-label="Delete">${
|
|
3014
|
+
<button type="button" class="__crossx-pin6-numpad-key --delete${_}" data-key="backspace" aria-label="Delete">${co}</button>
|
|
2558
3015
|
</div>
|
|
2559
3016
|
</div>`;return`
|
|
2560
3017
|
<div class="__crossx-header">
|
|
3018
|
+
<span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
|
|
2561
3019
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${S(s.title)}</p>
|
|
2562
3020
|
${t}
|
|
2563
3021
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
|
|
@@ -2568,7 +3026,7 @@ button.__crossx-connect-other-block:active {
|
|
|
2568
3026
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
2569
3027
|
${u}
|
|
2570
3028
|
<div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
|
|
2571
|
-
${
|
|
3029
|
+
${x}
|
|
2572
3030
|
</div>
|
|
2573
3031
|
</div>
|
|
2574
3032
|
${i}
|
|
@@ -2576,21 +3034,21 @@ button.__crossx-connect-other-block:active {
|
|
|
2576
3034
|
${c}
|
|
2577
3035
|
${o}
|
|
2578
3036
|
</div>
|
|
2579
|
-
${
|
|
2580
|
-
`}function _r(s,e){const r=document.createElement("div");return r.id=
|
|
3037
|
+
${g}
|
|
3038
|
+
`}function _r(s,e){const r=document.createElement("div");return r.id=Q,r.innerHTML=`
|
|
2581
3039
|
<div class="__crossx-card __crossx-card--pin6" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2582
3040
|
${e}
|
|
2583
3041
|
</div>
|
|
2584
|
-
`,r}function
|
|
3042
|
+
`,r}function oo(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function ao(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function wt(s,e,r,t,n,i,o){var P,G;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),u=()=>s.querySelector("#__crossx-pin6-boxes"),p=()=>s.querySelector("#__crossx-pin6-error"),x=()=>s.querySelector("#__crossx-pin6-lock-msg"),_=()=>s.querySelector("#__crossx-pin6-lock-countdown"),g=()=>s.querySelector(".__crossx-pin6-body"),w="●",b=(v,E)=>{v.dataset.digit=E,v.value=w},A=v=>{delete v.dataset.digit,v.value=""},T=v=>v.dataset.digit??"",C=()=>l().map(T).join(""),L=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),U=()=>{var R;const v=l(),E=L();if(E.length&&(E.forEach((I,F)=>{const V=!!(v[F]&&T(v[F]));I.classList.toggle("--filled",V),I.classList.toggle("--active",!1)}),!a&&!c)){const I=v.findIndex(V=>!T(V));(R=E[I===-1?5:I])==null||R.classList.add("--active")}},H=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(E=>E.classList.toggle("--disabled",a)),L().forEach(E=>E.classList.toggle("--locked",a)),U()},ee=v=>{a=v,l().forEach(E=>{E.disabled=v,E.classList.toggle("--locked",v)})},K=()=>s.querySelector("#__crossx-pin6-attempt"),J=()=>{const v=p();v&&(v.textContent="")},te=()=>o??"Your account will be locked after further failures.",q=()=>s.querySelector("#__crossx-pin6-warning"),B=v=>{var R;let E=q();if(!E){E=document.createElement("p"),E.className="__crossx-pin6-warning",E.id="__crossx-pin6-warning";const I=p();I?I.insertAdjacentElement("afterend",E):(R=g())==null||R.appendChild(E)}E.textContent=v},W=()=>{const v=q();v&&(v.textContent="")},y=(v,E)=>{var I;let R=K();if(!R){R=document.createElement("p"),R.className="__crossx-pin6-attempt",R.id="__crossx-pin6-attempt";const F=q()??p();F?F.insertAdjacentElement("afterend",R):(I=g())==null||I.appendChild(R)}R.textContent=`${v}/${E}`},m=()=>{const v=K();v&&(v.textContent="")},k=v=>{const E=p();E&&(E.textContent=v);const R=u();R==null||R.classList.add("--shake"),setTimeout(()=>R==null?void 0:R.classList.remove("--shake"),500),l().forEach(A),setTimeout(()=>{var I;(I=l()[0])==null||I.focus(),U()},50)},N=v=>{var V;ee(!0),l().forEach(A),H();const E=p();if(E&&(E.textContent="Too many failed attempts. Please wait."),!x()){const j=document.createElement("p");j.className="__crossx-pin6-lock-msg",j.id="__crossx-pin6-lock-msg",j.innerHTML=`${os}<span id="__crossx-pin6-lock-countdown"></span>`;const z=p();z?z.insertAdjacentElement("afterend",j):(V=g())==null||V.appendChild(j)}const R=()=>{var Y;const j=v-Date.now(),z=_();j<=0?(clearInterval(I),ee(!1),(Y=x())==null||Y.remove(),E&&(E.textContent=""),H(),setTimeout(()=>{var Ee;return(Ee=l()[0])==null?void 0:Ee.focus()},50)):z&&(z.textContent=` ${ao(j)}`)},I=setInterval(R,1e3);R();const F=new MutationObserver(()=>{document.contains(s)||(clearInterval(I),F.disconnect())});F.observe(document.body,{childList:!0,subtree:!1})},M=async()=>{if(a||c)return;const v=C();if(v.length===6){c=!0,l().forEach(E=>{E.disabled=!0});try{if(n){const E=await n(v);E.ok?e(v):E.lockExpiresAt?(m(),N(E.lockExpiresAt)):(k(E.error??"Incorrect PIN. Please try again."),E.attemptCount!=null&&E.maxAttempts!=null?(B(te()),y(E.attemptCount,E.maxAttempts)):(W(),m()))}else e(v)}catch(E){t&&t(E)}finally{c=!1,a||l().forEach(E=>{E.disabled=!1}),U()}}};i&&i>Date.now()?N(i):setTimeout(()=>{var v;return(v=l()[0])==null?void 0:v.focus()},100);const D=()=>{if(a||c)return;const v=l(),E=v.find(R=>!T(R))??v[v.length-1];E==null||E.focus()};(P=u())==null||P.addEventListener("click",v=>{v.target.classList.contains("__crossx-pin6-box")||D()}),(G=g())==null||G.addEventListener("click",v=>{const E=v.target;E.classList.contains("__crossx-pin6-box")||E.closest("button")||D()}),l().forEach((v,E)=>{v.addEventListener("input",()=>{var I;const R=v.value.replace(/\D/g,"").slice(-1);R?b(v,R):A(v),J(),R&&E<5&&((I=l()[E+1])==null||I.focus()),U(),C().length===6&&setTimeout(M,80)}),v.addEventListener("keydown",R=>{var I,F;if(R.key==="Backspace"){if(R.preventDefault(),T(v))A(v);else if(E>0){const V=l()[E-1];A(V),V.focus()}U()}else R.key==="ArrowLeft"&&E>0?(R.preventDefault(),(I=l()[E-1])==null||I.focus()):R.key==="ArrowRight"&&E<5?(R.preventDefault(),(F=l()[E+1])==null||F.focus()):R.key==="Escape"&&r()}),v.addEventListener("paste",R=>{var V,j;R.preventDefault();const I=(((V=R.clipboardData)==null?void 0:V.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const F=l();I.split("").forEach((z,Y)=>{F[Y]&&b(F[Y],z)}),(j=F[Math.min(I.length-1,5)])==null||j.focus(),J(),U(),C().length===6&&setTimeout(M,80)}),v.addEventListener("focus",()=>v.select())});const $=s.querySelector("#__crossx-pin6-numpad");if($){let v=null;const E=()=>{v&&(v.classList.remove("--pressed"),v=null)};$.addEventListener("pointerdown",I=>{const F=I.target.closest(".__crossx-pin6-numpad-key");!F||a||c||(E(),v=F,F.classList.add("--pressed"),F.setPointerCapture(I.pointerId))});const R=I=>{const F=I.dataset.key;if(!F)return;if(F==="backspace"){const Y=[...l()].reverse().find(Ee=>T(Ee));Y&&(A(Y),J()),U();return}if(!/^\d$/.test(F))return;const j=l().find(z=>!T(z));j&&(b(j,F),J(),U(),C().length===6&&setTimeout(M,80))};$.addEventListener("pointerup",I=>{if(!v)return;const F=v;E();const V=F.getBoundingClientRect();I.clientX>=V.left&&I.clientX<=V.right&&I.clientY>=V.top&&I.clientY<=V.bottom&&!a&&!c&&R(F)}),$.addEventListener("pointercancel",E),$.addEventListener("pointerleave",E,!0),U(),i&&i>Date.now()&&H()}}const co=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2585
3043
|
<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"/>
|
|
2586
3044
|
<line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
2587
3045
|
<line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
2588
|
-
</svg>`,
|
|
3046
|
+
</svg>`,os=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2589
3047
|
<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"/>
|
|
2590
|
-
</svg>`,
|
|
2591
|
-
<path d="M1 4.5L4 7.5L10 1" stroke="
|
|
2592
|
-
</svg>`,
|
|
3048
|
+
</svg>`,lo=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
3049
|
+
<path d="M1 4.5L4 7.5L10 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
3050
|
+
</svg>`,uo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2593
3051
|
<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"/>
|
|
2594
|
-
</svg>`;function oo(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,_)=>{t[_]&&(t[_].value=g)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class ao{constructor(e="light",r,t=Tt,n){this.theme=e,this.overrides=r,this.tokens=hr(e,r),this.displayDecimals=t,this.pinKeyboard=n}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=hr(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((n,i)=>{var R;ae();const o=[...e],a=Gi(o,this.tokens,t,this.messages),c=Ce();ce(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())};let p=null;const g=k=>{u(),n(k)},_=()=>{u(),p?i(p):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(k=>{k.addEventListener("click",()=>{const L=k.dataset.walletAddress??"",D=parseInt(k.dataset.walletIndex??"0",10),V=o.find(Q=>Q.index===D);g({address:L,index:D,name:V==null?void 0:V.name})})})})();const y=a.querySelector("#__crossx-add-wallet-error"),v=a.querySelector("#__crossx-add-wallet-btn");v&&v.addEventListener("click",async()=>{v.disabled=!0,y&&(y.hidden=!0,y.textContent="");try{const k=await r();o.push(k);const L=a.querySelector("#__crossx-wallet-list");if(L){const D=document.createElement("button");D.className="__crossx-wallet-item",D.dataset.walletIndex=String(k.index),D.dataset.walletAddress=k.address,D.innerHTML=`${ns(k.address,k.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${S(ss(k))}</span><span class="__crossx-wallet-addr">${de(k.address)}</span></span>`,D.addEventListener("click",()=>g(k)),L.appendChild(D);try{D.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}v.disabled=!1}catch(k){const L=k instanceof f&&k.code===h.ADDRESS_LIMIT_EXCEEDED,D=this.resolveAddWalletErrorMessage(k);y&&(y.textContent=D,y.hidden=!1),L?(v.disabled=!0,v.setAttribute("aria-disabled","true")):v.disabled=!1,p=k}}),(R=a.querySelector("#__crossx-close-btn"))==null||R.addEventListener("click",_),a.addEventListener("click",k=>{k.target===a&&_()});const A=k=>{k.key==="Escape"&&(document.removeEventListener("keydown",A),_())};document.addEventListener("keydown",A)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof f&&e.code===h.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:Xe;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}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(n=>Object.values(Le).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var g,_,x,y;ae();const i=ji(this.tokens,r,this.messages),o=Ce();ce(i);const a=()=>{i.remove(),o()},c=v=>{a(),n({type:"oauth",provider:v})},l=v=>{a(),n({type:"external",walletId:v})},u=()=>{a(),n(null)};(g=i.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>c("apple")),(_=i.querySelector("#__crossx-google-btn"))==null||_.addEventListener("click",()=>c("google")),(x=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||x.addEventListener("click",v=>{const R=v.currentTarget.dataset.walletId??"";R&&l(R)}),(y=i.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",u),i.addEventListener("click",v=>{v.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(v=>{v.addEventListener("click",A=>A.stopPropagation())});const p=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(r=>{var u,p,g;ae();const t=this.messages,n=Yi(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"}),i=Ce();ce(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;ae();const n=Xi(this.tokens,r);ce(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",g=>{g.target===n&&u()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(r=>{ae();const t=this.messages,n={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"},i={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."},o={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Enter your PIN again to confirm."},a=_r(this.tokens,eo(n)),c=Ce();ce(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},p=R=>{u(),r(R)},g=()=>{u(),r(null)},_=a.querySelector(".__crossx-card"),x={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."},y=R=>{var k;_.innerHTML=xt({title:o.title,headerSubtitle:o.headerSubtitle}),this.applyPinKeyboardMode(_),(k=_.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",g),wt(_,L=>{L===R?p(R):v(i.mismatchError)},g)},v=R=>{var k;_.innerHTML=xt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:R}),this.applyPinKeyboardMode(_),(k=_.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",g),wt(_,L=>{const D=to(L,x);D?v(D):y(L)},g)};(()=>{var te;const R=Array.from(_.querySelectorAll(".__crossx-pw-notice-item")),k=_.querySelector("#__crossx-pin-notice-next"),L=new Set;k.removeAttribute("disabled");const D=k.dataset.nextLabel??"Next",V=k.dataset.submitLabel??"I Understand",Q=()=>{const G=L.size===R.length;k.classList.toggle("--disabled",!G),k.textContent=G?V:D},q=(G,B)=>{if(L.has(B))return;const H=G.querySelector(`#__crossx-notice-check-${B}`);L.add(B),H.classList.add("--checked"),G.setAttribute("aria-checked","true"),Q()},J=(G,B)=>{if(!L.has(B))return;const H=G.querySelector(`#__crossx-notice-check-${B}`);L.delete(B),H.classList.remove("--checked"),G.setAttribute("aria-checked","false"),Q()};R.forEach(G=>{const B=parseInt(G.dataset.checkIndex??"0",10);G.addEventListener("click",()=>{L.has(B)?J(G,B):q(G,B)}),G.addEventListener("keydown",H=>{(H.key===" "||H.key==="Enter")&&(H.preventDefault(),L.has(B)?J(G,B):q(G,B))})}),k.addEventListener("click",()=>{if(L.size===R.length){v(e==null?void 0:e.errorMessage);return}const G=R.find(H=>{const m=parseInt(H.dataset.checkIndex??"0",10);return!L.has(m)});if(!G)return;const B=parseInt(G.dataset.checkIndex??"0",10);G.scrollIntoView({behavior:"smooth",block:"nearest"}),G.classList.add("--highlight"),setTimeout(()=>{G.classList.remove("--highlight"),q(G,B)},400)}),(te=_.querySelector("#__crossx-close-btn"))==null||te.addEventListener("click",g)})(),a.addEventListener("click",R=>{R.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var A;ae();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verify_pin_title)??"Verify Your PIN":(n==null?void 0:n.pin_input_title)??"Enter PIN",a=i?(n==null?void 0:n.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pin_locked_failure_warning)??"Your account will be locked after further failures.",l=_r(this.tokens,xt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=Ce();ce(l);let p=!1;const g=()=>{p||(p=!0,l.remove(),u())},_=R=>{g(),r(R)},x=()=>{g(),r(null)},y=R=>{g(),t(R)},v=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(v),(A=v.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",x),wt(v,_,x,y,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;ae();const t=Ji(this.tokens,e);ce(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),oo(t,i,o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.addEventListener("click",l=>{l.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;ae();const{overlay:n,startCountdown:i}=Qi(this.tokens,e,r);ce(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;ae();const t=Pi(e,this.tokens,this.messages);ce(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var g;u.stopPropagation();const p=l.dataset.copy;p&&((g=navigator.clipboard)==null||g.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{ae();const n=Li(e,this.tokens,this.messages);ce(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,p;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(Di(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,u,p;ae();let t;e.type==="sign-message"?t=$i(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Bi(e,this.tokens,this.messages):e.type==="sign"?t=Ii(e,this.tokens,this.displayDecimals,this.messages):t=Ti(e,this.tokens,this.displayDecimals,this.messages);const n=Ce();ce(t);const i=()=>{t.remove(),n()},o=()=>{i(),r(!0)},a=()=>{i(),r(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",_=>{var y;_.stopPropagation();const x=g.dataset.copy;x&&((y=navigator.clipboard)==null||y.writeText(x).catch(()=>{}))})}),fi(t),t.addEventListener("click",g=>{g.target===t&&a()});const c=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class co{constructor(e,r,t,n=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=n}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:n,chainId:i}=this.mapToNativeParams(e),o={operation:t,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await r.requestUserConfirmation(o)}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 f(h.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 n=this.getBridge();if(this.shouldDelegateToBridge()&&(n!=null&&n.showWalletSelector))try{const i=await n.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===i.address.toLowerCase());return{address:i.address,index:(o==null?void 0:o.index)??i.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t)}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 os{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 lo(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
|
|
3052
|
+
</svg>`;function ho(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((x,_)=>{t[_]&&(t[_].value=x)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class po{constructor(e="light",r,t=kt,n){this.theme=e,this.overrides=r,this.tokens=hr(e,r),this.displayDecimals=t,this.pinKeyboard=n}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=hr(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((n,i)=>{var T;ae();const o=[...e],a=zi(o,this.tokens,t,this.messages),c=Ie();ce(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())};let p=null;const x=C=>{u(),n(C)},_=()=>{u(),p?i(p):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(C=>{C.addEventListener("click",()=>{const L=C.dataset.walletAddress??"",U=parseInt(C.dataset.walletIndex??"0",10),H=o.find(ee=>ee.index===U);x({address:L,index:U,name:H==null?void 0:H.name})})})})();const w=a.querySelector("#__crossx-add-wallet-error"),b=a.querySelector("#__crossx-add-wallet-btn");b&&b.addEventListener("click",async()=>{b.disabled=!0,w&&(w.hidden=!0,w.textContent="");try{const C=await r();o.push(C);const L=a.querySelector("#__crossx-wallet-list");if(L){const U=document.createElement("button");U.className="__crossx-wallet-item",U.dataset.walletIndex=String(C.index),U.dataset.walletAddress=C.address,U.innerHTML=`${is(C.address,C.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${S(ns(C))}</span><span class="__crossx-wallet-addr">${Jr(C.address)}</span></span>`,U.addEventListener("click",()=>x(C)),L.appendChild(U);try{U.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}b.disabled=!1}catch(C){const L=C instanceof f&&C.code===h.ADDRESS_LIMIT_EXCEEDED,U=this.resolveAddWalletErrorMessage(C);w&&(w.textContent=U,w.hidden=!1),L?(b.disabled=!0,b.setAttribute("aria-disabled","true")):b.disabled=!1,p=C}}),(T=a.querySelector("#__crossx-close-btn"))==null||T.addEventListener("click",_),a.addEventListener("click",C=>{C.target===a&&_()});const A=C=>{C.key==="Escape"&&(document.removeEventListener("keydown",A),_())};document.addEventListener("keydown",A)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,c;ae();const r=ji(this.tokens,this.messages),t=Ie();ce(r);let n=!1,i=null;const o=()=>{n||(n=!0,i&&document.removeEventListener("keydown",i),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",o),(c=r.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),r.addEventListener("click",l=>{l.target===r&&o()}),i=l=>{l.key==="Escape"&&o()},document.addEventListener("keydown",i)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof f&&e.code===h.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:Xe;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}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(n=>Object.values(Le).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var x,_,g,w;ae();const i=Qi(this.tokens,r,this.messages),o=Ie();ce(i);const a=()=>{i.remove(),o()},c=b=>{a(),n({type:"oauth",provider:b})},l=b=>{a(),n({type:"external",walletId:b})},u=()=>{a(),n(null)};(x=i.querySelector("#__crossx-apple-btn"))==null||x.addEventListener("click",()=>c("apple")),(_=i.querySelector("#__crossx-google-btn"))==null||_.addEventListener("click",()=>c("google")),(g=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||g.addEventListener("click",b=>{const T=b.currentTarget.dataset.walletId??"";T&&l(T)}),(w=i.querySelector("#__crossx-close-btn"))==null||w.addEventListener("click",u),i.addEventListener("click",b=>{b.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(b=>{b.addEventListener("click",A=>A.stopPropagation())});const p=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(r=>{var u,p,x;ae();const t=this.messages,n=eo(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"}),i=Ie();ce(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(x=n.querySelector("#__crossx-close-btn"))==null||x.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;ae();const n=to(this.tokens,r);ce(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",x=>{x.target===n&&u()});const p=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(r=>{ae();const t=this.messages,n={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"},i={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."},o={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=_r(this.tokens,io(n)),c=Ie();ce(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},p=T=>{u(),r(T)},x=()=>{u(),r(null)},_=a.querySelector(".__crossx-card"),g={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."},w=T=>{var C;_.innerHTML=gt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(_),(C=_.querySelector("#__crossx-close-btn"))==null||C.addEventListener("click",x),wt(_,L=>{L===T?p(T):b(i.mismatchError)},x)},b=T=>{var C;_.innerHTML=gt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:T}),this.applyPinKeyboardMode(_),(C=_.querySelector("#__crossx-close-btn"))==null||C.addEventListener("click",x),wt(_,L=>{const U=oo(L,g);U?b(U):w(L)},x)};(()=>{var te;const T=Array.from(_.querySelectorAll(".__crossx-pw-notice-item")),C=_.querySelector("#__crossx-pin-notice-next"),L=new Set;C.removeAttribute("disabled");const U=C.dataset.nextLabel??"Next",H=C.dataset.submitLabel??"I Understand",ee=()=>{const q=L.size===T.length;C.classList.toggle("--disabled",!q),C.textContent=H||U},K=(q,B)=>{if(L.has(B))return;const W=q.querySelector(`#__crossx-notice-check-${B}`);L.add(B),W.classList.add("--checked"),q.setAttribute("aria-checked","true"),ee()},J=(q,B)=>{if(!L.has(B))return;const W=q.querySelector(`#__crossx-notice-check-${B}`);L.delete(B),W.classList.remove("--checked"),q.setAttribute("aria-checked","false"),ee()};T.forEach(q=>{const B=parseInt(q.dataset.checkIndex??"0",10);q.addEventListener("click",()=>{L.has(B)?J(q,B):K(q,B)}),q.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),L.has(B)?J(q,B):K(q,B))})}),C.addEventListener("click",()=>{if(L.size===T.length){b(e==null?void 0:e.errorMessage);return}const q=T.find(W=>{const y=parseInt(W.dataset.checkIndex??"0",10);return!L.has(y)});if(!q)return;const B=parseInt(q.dataset.checkIndex??"0",10);q.scrollIntoView({behavior:"smooth",block:"nearest"}),q.classList.add("--highlight"),setTimeout(()=>{q.classList.remove("--highlight"),K(q,B)},400)}),(te=_.querySelector("#__crossx-close-btn"))==null||te.addEventListener("click",x)})(),a.addEventListener("click",T=>{T.target===a&&x()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var A;ae();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verify_pin_title)??"Verify Your PIN":(n==null?void 0:n.pin_input_title)??"Enter PIN",a=i?(n==null?void 0:n.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pin_locked_failure_warning)??"Your account will be locked after further failures.",l=_r(this.tokens,gt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=Ie();ce(l);let p=!1;const x=()=>{p||(p=!0,l.remove(),u())},_=T=>{x(),r(T)},g=()=>{x(),r(null)},w=T=>{x(),t(T)},b=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(b),(A=b.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),wt(b,_,g,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",T=>{T.target===l&&g()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;ae();const t=ro(this.tokens,e);ce(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),ho(t,i,o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.addEventListener("click",l=>{l.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;ae();const{overlay:n,startCountdown:i}=no(this.tokens,e,r);ce(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;ae();const t=$i(e,this.tokens,this.messages);ce(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var x;u.stopPropagation();const p=l.dataset.copy;p&&((x=navigator.clipboard)==null||x.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{ae();const n=Mi(e,this.tokens,this.messages);ce(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,p;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",x=>{x.target===n&&a()});const l=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(Fi(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,u,p;ae();let t;e.type==="sign-message"?t=Ui(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Hi(e,this.tokens,this.messages):e.type==="sign"?t=Ti(e,this.tokens,this.displayDecimals,this.messages):t=Ni(e,this.tokens,this.displayDecimals,this.messages);const n=Ie();ce(t);const i=()=>{t.remove(),n()},o=()=>{i(),r(!0)},a=()=>{i(),r(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",_=>{var w;_.stopPropagation();const g=x.dataset.copy;g&&((w=navigator.clipboard)==null||w.writeText(g).catch(()=>{}))})}),xi(t),t.addEventListener("click",x=>{x.target===t&&a()});const c=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class _o{constructor(e,r,t,n=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=n}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:n,chainId:i}=this.mapToNativeParams(e),o={operation:t,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await r.requestUserConfirmation(o)}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 f(h.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 n=this.getBridge();if(this.shouldDelegateToBridge()&&(n!=null&&n.showWalletSelector))try{const i=await n.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===i.address.toLowerCase());return{address:i.address,index:(o==null?void 0:o.index)??i.index,name:o==null?void 0:o.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 as{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 fo(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
|
|
2595
3053
|
Set the projectId field in SDKConfig when calling createCROSSxSDK().
|
|
2596
|
-
Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=De.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&jt.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new jt(s.projectId):new
|
|
3054
|
+
Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=De.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&jt.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new jt(s.projectId):new Ys,a=new ni,c=new ci,l=new ke,u=new as,p=new It;let x;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),x=new di(o,p)):(d.log("[CROSSx] Remote Wallet Provider 사용"),x=new Te(n,o,c,u,p));let _=null;const g=()=>{var H;return((H=_==null?void 0:_.isAuthenticatedViaRNBridge)==null?void 0:H.call(_))??!1},w=()=>{var H;return(H=_==null?void 0:_.assertRNBridgeSessionActive)==null?void 0:H.call(_)};x=new ui(x,()=>{var H;return(H=_==null?void 0:_.getRNBridge)==null?void 0:H.call(_)},g,w);const b=new We(n,c),A=new po(s.theme??"light",s.themeTokens,s.displayDecimals,s.pinKeyboard),T=new _o(A,()=>{var H;return(H=_==null?void 0:_.getRNBridge)==null?void 0:H.call(_)},()=>typeof window<"u"?window.location.origin:"http://localhost",g),C=e!=null&&e.wrapConfirmation?e.wrapConfirmation(T):T,L=new Je(t,n,o,a,c,l,x,u,C,b,p);_=L;const U=L.signInUseCase;return U&&typeof U.setFreshTokenCallback=="function"&&U.setFreshTokenCallback(()=>L.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=L),L}function xo(s){const e=go(s),r=wo(e),t=JSON.parse(r);yo(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function go(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),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 s}function wo(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=mo(s);return decodeURIComponent(e)}function mo(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function yo(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;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=fr;exports.CROSSxError=f;exports.CROSSxEthereumProvider=gr;exports.CROSSxSDK=Je;exports.ChainId=hs;exports.ConnectOtherWalletItem=Le;exports.ErrorCode=h;exports.MNEMONIC_ADDRESS_LIMIT=Xe;exports.PinMemoryStore=It;exports.TokenMemoryStore=as;exports.createCROSSxSDK=fo;exports.getConnectOtherWalletLabel=xr;exports.parseOAuthDeeplink=xo;
|