@nexus-cross/crossx-sdk-core 2.5.0-beta.1 → 2.6.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.
@@ -1,13 +1,110 @@
1
- var CROSSx=(function(J){"use strict";var qc=Object.defineProperty;var zc=(J,h,f)=>h in J?qc(J,h,{enumerable:!0,configurable:!0,writable:!0,value:f}):J[h]=f;var P=(J,h,f)=>zc(J,typeof h!="symbol"?h+"":h,f);var Ct,bn;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.EXECUTION_REVERTED="EXECUTION_REVERTED",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.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",s.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",s.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",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}}}const vn=2e3,br=6e4,En=1e3,An=1e4,In="0x77359400",Sr="0x3B9ACA00",vr=130,Ot=6,Er=18,Ar=3e4,Rn=300*1e3,Tn=30*1e3,lt=100,kn=300*1e3,Ir=60*1e3,Nn="crossx-sdk-js/2.5.0-beta.1",dt="ONEpocket";var We=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(We||{});const Cn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:dt},Rr=["crossx","io.metamask","com.binance.wallet"];function Tr(s){return Cn[s]??s}function On(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...Rr]:[]}function kr(s){const e=s instanceof Error?s.message:String(s);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const Pn=new Set(["ERR_USER_REJECTED","USER_REJECTED","USER_REJECT"]),Dn=/user rejected|rejected the request|request (?:was )?cancell?ed|entry was cancell?ed|거부했습니다|취소되었습니다/i;function Nr(s){if(!s||typeof s!="object")return;const e=s.code;return typeof e=="string"&&e.length>0?e:void 0}function Ln(s){const e=Nr(s);if(e)return Pn.has(e);const r=s instanceof Error?s.message:String(s);return Dn.test(r)}function He(s,e){if(s instanceof f)return s;const r=Nr(s),t=s instanceof Error?s.message:String(s),n={nativeCode:r,cause:s};if(Ln(s))return new f(h.USER_REJECTED,t,n);const i=r&&!t.includes(r)?`${t} (${r})`:t;return new f(e,i,n)}const ut={ONE_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"ONEchain Mainnet",nativeCurrency:{symbol:"ONE",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},ONE_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Bn=Object.fromEntries(Object.entries(ut).map(([s,e])=>[s,e.caipId])),Mn=new Map(Object.values(ut).map(s=>[s.caipId,s]));new Map(Object.values(ut).map(s=>[s.chainId,s]));const $n={symbol:"",decimals:18};function Fn(s,e){var r;return(e==null?void 0:e[s])??((r=Mn.get(s))==null?void 0:r.nativeCurrency)}class Pt{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 ye=null;function Jc(s){}function Cr(s){ye=s}const d={info(...s){if(ye){ye.log(...s);return}console.log(...s)},log(...s){if(ye){ye.log(...s);return}},warn(...s){if(ye){ye.warn(...s);return}},error(...s){if(ye){ye.error(...s);return}}},Un={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:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
1
+ var CROSSx=(function(X){"use strict";var $l=Object.defineProperty;var Ul=(X,h,_)=>h in X?$l(X,h,{enumerable:!0,configurable:!0,writable:!0,value:_}):X[h]=_;var P=(X,h,_)=>Ul(X,typeof h!="symbol"?h+"":h,_);var Mt,Fn;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.ONEID_TERMS_NOT_AGREED="ONEID_TERMS_NOT_AGREED",s.ONEID_ACCOUNT_NOT_FOUND="ONEID_ACCOUNT_NOT_FOUND",s.ONEID_SERVICE_NOT_LINKED="ONEID_SERVICE_NOT_LINKED",s.ONEID_AUTHORIZATION_FAILED="ONEID_AUTHORIZATION_FAILED",s.ONEID_STATE_MISMATCH="ONEID_STATE_MISMATCH",s.ONEID_ISSUER_MISMATCH="ONEID_ISSUER_MISMATCH",s.ONEID_TIMEOUT="ONEID_TIMEOUT",s.ONEID_SESSION_EVICTED="ONEID_SESSION_EVICTED",s.ONEID_SESSION_REVOKED="ONEID_SESSION_REVOKED",s.ONEID_SESSION_EXPIRED="ONEID_SESSION_EXPIRED",s.ONEID_SESSION_INVALID="ONEID_SESSION_INVALID",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.SDK_VERSION_UNSUPPORTED="SDK_VERSION_UNSUPPORTED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.EXECUTION_REVERTED="EXECUTION_REVERTED",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.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",s.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",s.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",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 _ extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Hn=2e3,Or=6e4,Gn=1e3,Kn=1e4,Vn="0x77359400",kr="0x3B9ACA00",Pr=130,$t=6,Dr=18,Lr=3e4,qn=300*1e3,zn=30*1e3,dt=100,Jn=300*1e3,Br=60*1e3,ut="crossx-sdk-js/2.6.0-beta.1",jn="X-SDK-Version",Yn=!1,Xn="x-sdk-deprecation",ht=-10050,pt="ONEpocket";var We=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(We||{});const Zn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:pt},Mr=["crossx","io.metamask","com.binance.wallet"];function $r(s){return Zn[s]??s}function Qn(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...Mr]:[]}function Ur(s){const e=s instanceof Error?s.message:String(s);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const ei=new Set(["ERR_USER_REJECTED","USER_REJECTED","USER_REJECT"]),ti=/user rejected|rejected the request|request (?:was )?cancell?ed|entry was cancell?ed|거부했습니다|취소되었습니다/i;function Fr(s){if(!s||typeof s!="object")return;const e=s.code;return typeof e=="string"&&e.length>0?e:void 0}function ri(s){const e=Fr(s);if(e)return ei.has(e);const r=s instanceof Error?s.message:String(s);return ti.test(r)}function He(s,e){if(s instanceof _)return s;const r=Fr(s),t=s instanceof Error?s.message:String(s),n={nativeCode:r,cause:s};if(ri(s))return new _(h.USER_REJECTED,t,n);const i=r&&!t.includes(r)?`${t} (${r})`:t;return new _(e,i,n)}const _t={ONE_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"ONEchain Mainnet",nativeCurrency:{symbol:"ONE",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},ONE_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},si=Object.fromEntries(Object.entries(_t).map(([s,e])=>[s,e.caipId])),ni=new Map(Object.values(_t).map(s=>[s.caipId,s]));new Map(Object.values(_t).map(s=>[s.chainId,s]));const ii={symbol:"",decimals:18};function oi(s,e){var r;return(e==null?void 0:e[s])??((r=ni.get(s))==null?void 0:r.nativeCurrency)}class Ut{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new _(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new _(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 ye=null;function Fl(s){}function Wr(s){ye=s}const u={info(...s){if(ye){ye.log(...s);return}console.log(...s)},log(...s){if(ye){ye.log(...s);return}},warn(...s){if(ye){ye.warn(...s);return}},error(...s){if(ye){ye.error(...s);return}}},ai={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_empty:"아직 지갑이 없습니다. 지갑을 추가해 주세요.",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:"다시 로그인"},Or={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:dt,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 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.
4
+ 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,update_required_title:"업데이트 필요",update_required_message:"이 서비스가 더 이상 지원하지 않는 지갑 버전을 사용하고 있어 지금은 로그인하거나 전송할 수 없습니다. 서비스가 업데이트된 뒤 다시 시도해 주세요.",update_required_confirm_button:"확인",session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},Hr={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:pt,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 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_empty:"No wallet yet. Add a wallet to continue.",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"},Wn={ko:Un,en:Or};function be(s="en",e){return Wn[s]??Or}function Hn(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Pr="crossx_access_token",Dr="crossx_refresh_token",Lr="crossx_user_info",Nt=class Nt{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,legacyOauthServiceUrl:a}=this.config,c=Hn(this.getLocale()),l=x=>{const w=`${x}${i}`,g=w.includes("?")?"&":"?";return`${w}${g}locale=${c}`},u=l(o),p=a?l(a):void 0;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const _=await this.oauth.openAuth({authUrl:u,...p?{legacyAuthUrl:p}:{},expectedOrigin:new URL(o).origin});r=_.token,t=_.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){if(d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n),n instanceof f)throw 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:_}=await this.exchangeFirebaseToken(e,u);let x,w,g;try{const E=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(E).join(", ")),w=(i=E.firebase)==null?void 0:i.sign_in_provider;const I=((o=E.firebase)==null?void 0:o.identities)??{};g=E.email??((a=I.email)==null?void 0:a[0]),w==="google.com"?x=(c=I["google.com"])==null?void 0:c[0]:w==="apple.com"&&(x=(l=I["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",w,"hasProviderSub:",!!x,"email:",g??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const E=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",E.sub,"exp:",E.exp,"필드:",Object.keys(E).join(", "));const I=await this.crypto.verifyJWT(p);if(n=I.signatureVerified??!1,!I.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const N=I.payload,L=N.email??g??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",N.email??"(없음)","/ Firebase JWT:",g??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:N.sub,email:L,signInProvider:w,providerSub:x},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const E=this.crypto.decodeJWT(e);t={id:E.sub,email:E.email??r,signInProvider:w,providerSub:x},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const m=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,m),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=Nt.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(Lr);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(Pr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Dr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Lr),await this.storage.remove(Pr),await this.storage.remove(Dr),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}}};Nt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Dt=Nt;class Kn{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 Gn{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 Lt{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}}const Vn=3,qn=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function zn(s){return s.code===Vn||/execution reverted/i.test(s.message??"")}class Jn{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){const{code:c,message:l}=a.error,u={method:e,chainId:t,code:c,message:l,data:a.error.data},p=zn(a.error);throw p&&typeof u.data=="string"&&qn.test(u.data)&&(u.revertData=u.data,u.selector=u.data.slice(0,10).toLowerCase()),new f(p?h.EXECUTION_REVERTED:h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${l} (코드: ${c})`,u)}return a==null?void 0:a.result}}class Yn{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 jn(){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=jn(),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,a=n.provider==="google"||n.provider==="apple"?n.provider: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,walletProvider:a}}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.")}}var ht={environment:"production"};const Ke={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher"},staging:{oauthServiceUrl:"https://stg-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher"},development:{oauthServiceUrl:"https://dev-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher"}};function Xn(s){const e=s.environment,r=e&&e in Ke?Ke[e]:null;if(!r)return null;const t=s.overrides;if(!t)return r;const n={...r};for(const[i,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(n[i]=o);return n}function Bt(){try{if(typeof ht<"u"){const s=typeof ht=="string"?JSON.parse(ht):ht,e=Xn(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Ke)return Ke[s]}catch{}return Ke.production}function Br(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Zn(s,e=Ot){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Er),n=r/t,o=(r%t).toString().padStart(Er,"0"),a=Br(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function pt(s,e,r,t=Ot){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=Br(c.slice(0,t)),u=l?`${o}.${l}`:`${o}`;return e?`${u} ${e}`:u}catch{return}}function Qn(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!==vr)throw new f(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${vr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function ei(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 ti(s,e){const r=ri(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 ri(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 Ge{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){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){var c,l;if((l=(c=this.deps).isRNBridgeMode)!=null&&l.call(c))return;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((u,p)=>{i=u,o=p});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const p=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!p)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(p),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const u=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async p=>{this.deps.pinStore.set(p);try{return await this.deps.walletProvider.verifyPin(p)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(_){if(this.deps.pinStore.clear(),_ instanceof f){if(_.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(_.code===h.PIN_INVALID)return{ok:!1,error:_.message};if(_.code===h.PIN_LOCKED)return Ge.buildPinLockedResult(_,a)}throw _}}});if(!u)throw new f(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(u),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(u){if(u instanceof f&&(u.code===h.AUTH_NOT_AUTHENTICATED||u.code===h.AUTH_TOKEN_EXPIRED||u.code===h.SESSION_EXPIRED)&&u.code!==h.SESSION_EXPIRED){const p=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:_?this.deps.maskEmail(_,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(u),u}throw o(u),u}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof f){if(t=Ge.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=Ge.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=Ge.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class si{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 ni(s){return s==="google"||s==="apple"}class ii{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=ni(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=be(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=be(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 oi{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(_=>_.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 ai{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 _=p.pinStatus;if(o=_.maxAttempts,i=o-_.remainingAttempts,_.remainingAttempts===0&&_.lockExpiresAt){const x=_.lockExpiresAt*1e3,w=Math.max(1,Math.round((x-Date.now())/1e3)),g=w<=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 잠금 — ${w}초, 메시지: ${g}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,g),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 _=be(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:x?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 _=p.details;if(o=(_==null?void 0:_.maxAttempts)??5,(_==null?void 0:_.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const x=((_==null?void 0:_.lockExpiresAt)??0)*1e3,w=Math.max(1,Math.round((x-Date.now())/1e3)),g=w<=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 이미 잠금 — ${w}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,g),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=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:_?this.deps.maskEmail(_,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const g=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",g.address),g}catch(g){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",g),g}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class ci{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=x=>!(x!=null&&x.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,_]=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(x){const w=Sr;c.maxFeePerGas=`0x${(BigInt(x)+BigInt(w)).toString(16)}`,c.maxPriorityFeePerGas=w,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",x,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=In,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=Sr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class li{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 di(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class ui{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,r){var n,i,o,a,c;const t={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:di((a=e.user)==null?void 0:a.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(t),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...r?{source:r}:{}})}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 hi{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 pi{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 fi{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 Mr(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class _i{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=Mr(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(Mr(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 Mt(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 Fe=class Fe extends Yn{constructor(e,r,t,n,i,o,a,c,l,u,p,_){var x,w;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.pinEncryptor=_,this._warnedUnknownNativeCurrency=new Set,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&&Cr(e.logger),this.confirmation=l,this.pinStore=p??new Lt,this.stateManager=new ui({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:m,walletName:E})=>{const I={address:g,index:m};E!==void 0&&(I.walletName=E),this.emit("addressChanged",I)},emitAuthChanged:({isAuthenticated:g,address:m,userId:E,source:I})=>{this.emit("authChanged",{isAuthenticated:g,address:m,userId:E,...I?{source:I}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Fe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ge({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Mt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new si({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new oi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(g,m,E)=>this.setActiveWallet(g,m,E)}),this.migrationOrchestrator=new ai({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(g,m)=>this.migrateWalletUseCase.execute(g,m),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Mt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var g;return((g=this._config.migration)==null?void 0:g.allowSkip)??!0}}),this.transactionLifecycleService=new ci({getActiveAddress:()=>this.address,estimateGas:(g,m)=>this.estimateGas(g,m),getBaseFeePerGas:g=>this.getBaseFeePerGas(g),jsonRpcCall:(g,m,E)=>this.jsonRpc.call(g,m,E)}),this.signatureVerifier=new li(this.crypto),this.addressResolverService=new hi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new pi({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new fi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(g,m)=>this.setActiveWallet(g,m),showWalletCreated:()=>{var g,m;return((m=(g=this.confirmation).showWalletCreatedPrompt)==null?void 0:m.call(g))??Promise.resolve()}}),this.tokenHistoryService=new _i({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new ii({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:Mt}),this.chainRegistry=u,this.jsonRpc=new Jn(u,i),this.signInUseCase=new Dt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new Kn(this.internalConfig,t,c),this.migrateWalletUseCase=new Gn(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(w=a.setTokenRefresher)==null||w.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,d.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(r){d.warn("[CROSSx] 저장된 bridge 세션 마커 제거 실패",r)}}}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.5.0-beta.1 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=Bt();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=n.legacyOauthServiceUrl,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(Fe.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)d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(p instanceof f&&(p.code===h.SESSION_EXPIRED||p.code===h.AUTH_NOT_AUTHENTICATED||p.code===h.USER_NOT_FOUND))d.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",p.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw p}}return this.initialized=!0,d.info("[CROSSx SDK] v2.5.0-beta.1 초기화 완료"),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 시도"),d.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.5.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new _e({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.5.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),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.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const r=this._rnBridgeService.getContext(),t=Date.now();d.info("[CROSSx] Bridge 세션 만료 감지 — 재핸드셰이크 시도",{elapsedSinceActivatedMs:r?t-r.activatedAt:"(context 없음)",idleMs:r?t-r.lastActivityAt:"(context 없음)",absoluteTtlMs:(r==null?void 0:r.absoluteTtlMs)??"(context 없음)",idleTtlMs:(r==null?void 0:r.idleTtlMs)??"(context 없음)",absoluteExpired:r?t-r.activatedAt>r.absoluteTtlMs:"(context 없음)",idleExpired:r?t-r.lastActivityAt>r.idleTtlMs:"(context 없음)"});try{const n=Date.now(),i=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=i.walletAddress,this._rnBridgeWalletName=i.walletName,this._rnBridgeWalletProvider=i.walletProvider,d.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-n,walletAddress:i.walletAddress??"(없음)",walletName:i.walletName??"(없음)",absoluteTtlMs:i.absoluteTtlMs,idleTtlMs:i.idleTtlMs})}catch(n){return d.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",n),this._rnBridgeService=null,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?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):r instanceof f&&r.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),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())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,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):(this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return this._isAuthenticatedViaRNBridge=!1,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()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&d.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let t=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:On(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new f(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(t);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof f?n:new f(h.AUTH_FAILED,"로그인에 실패했습니다",n)}}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){var t,n;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,"external"),(n=(t=this.oauth).cancelPending)==null||n.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof f?i:new f(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c);return{...r,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:i}}catch(i){throw i instanceof f&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),i}}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(be(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}resolveNativeCurrency(e){const r=Fn(e,this._config.nativeCurrencies);return r||(this._warnedUnknownNativeCurrency.has(e)||(this._warnedUnknownNativeCurrency.add(e),console.warn(`[CROSSx SDK] ${e} 의 native 통화 정보가 없어 심볼을 비우고 decimals 를 18 로 가정합니다. 컨펌 모달 금액이 단위 없이 표시되며, decimals 가 18 이 아니면 금액이 틀립니다. SDKConfig.nativeCurrencies 에 { '${e}': { symbol, decimals } } 를 넘겨 주세요.`)),$n)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const n=_e.getBridge(),i=this._isAuthenticatedViaRNBridge||!this.authenticated;if(n!=null&&n.signMessage&&i)try{const a=await n.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:a.signature,message:r,address:this.address??""}}catch(a){if(!kr(a))throw He(a,h.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),d.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new f(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const o=await this.resolveAddress(t==null?void 0:t.index);try{const a=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:o.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:o.address},execute:c=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,c,o.address)});return this.signatureVerifier.verifySignatureSigner(r,a.signature,o.address),{chainId:e,signature:a.signature,message:r,address:o.address}}catch(a){throw a instanceof f?a:new f(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,a)}}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가 구현되어 있지 않습니다");ti(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 Qn(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(Fe.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=this.resolveNativeCurrency(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 ei(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=this.resolveNativeCurrency(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,Nn).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??En,i=An,o=t.timeoutMs??br,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 g,m;if(this._isAuthenticatedViaRNBridge){const E=_e.getBridge();if(E!=null&&E.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(E,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((g=this._config.receiptPolling)==null?void 0:g.intervalMs)??vn,l=i??((m=this._config.receiptPolling)==null?void 0:m.timeoutMs)??br,u=this.resolveNativeCurrency(e),p=r.from??"";let _,x;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{_=E;const I=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),N=r.value?BigInt(r.value):0n,L=pt(r.value,u.symbol,u.decimals,this._config.displayDecimals),W=pt("0x"+I.toString(16),u.symbol,u.decimals,this._config.displayDecimals),z=pt("0x"+(N+I).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:E.from,to:E.to??r.to,amount:L,fees:W,total:z,nativeSymbol:u.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(x=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:p,to:r.to,amount:pt(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},w),x)throw x;return{chainId:e,txHash:a,receipt:_}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){let i;try{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??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs})}catch(o){throw He(o,h.TRANSACTION_FAILED)}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){if(n instanceof f&&n.code===h.EXECUTION_REVERTED)throw 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:Zn(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 Pt(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&&!this._isAuthenticatedViaRNBridge){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,r){this.stateManager.applyAuthResult(e,r)}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(),Cr(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig,pinEncryptor:this.pinEncryptor}}};Fe.WALLET_PREF_KEY="wallet_preference",Fe.OFFCHAIN_CHAIN_ID="0";let et=Fe;class gi{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 ft="crossx-sdk",$r=1,he="data",Te="keys",_t="aes-primary",xi=12;class Fr{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(){return new Promise((e,r)=>{const t=indexedDB.open(this.dbName,$r);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(he)||n.createObjectStore(he),n.objectStoreNames.contains(Te)||n.createObjectStore(Te)},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error)})}openLegacyIfExists(){return new Promise((e,r)=>{let t=!1;const n=indexedDB.open(ft,$r);n.onupgradeneeded=()=>{t=!0},n.onsuccess=()=>{const i=n.result;if(t){i.close(),this.deleteDB(ft).then(()=>e(null));return}if(!i.objectStoreNames.contains(Te)||!i.objectStoreNames.contains(he)){i.close(),e(null);return}e(i)},n.onerror=()=>r(n.error)})}deleteDB(e){return new Promise(r=>{const t=indexedDB.deleteDatabase(e);t.onsuccess=()=>r(),t.onerror=()=>{d.warn("[CROSSx] IndexedDB 삭제 실패:",e,t.error),r()},t.onblocked=()=>{d.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),r()}})}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(Te,_t);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Te,_t,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===ft)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const r=e.transaction([Te,he],"readonly"),t=r.objectStore(Te).get(_t),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(he).getAll(),o=r.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Te,_t,n);for(let l=0;l<c.length;l++)await this.idbPut(he,String(c[l]),a[l]);return await this.deleteDB(ft),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(xi);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(he,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(he,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(he,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(he)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const $t=crypto,Ur=s=>s instanceof CryptoKey,gt=new TextEncoder,tt=new TextDecoder;function wi(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const mi=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},ke=s=>{let e=s;e instanceof Uint8Array&&(e=tt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return mi(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class se extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}se.code="ERR_JOSE_GENERIC";class pe extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}pe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Ft extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Ft.code="ERR_JWT_EXPIRED";class Wr extends se{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Wr.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends se{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class yi extends se{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}yi.code="ERR_JWE_DECRYPTION_FAILED";class bi extends se{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}bi.code="ERR_JWE_INVALID";class te extends se{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}te.code="ERR_JWS_INVALID";class xe extends se{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class Si extends se{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Si.code="ERR_JWK_INVALID";class Ut extends se{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Ut.code="ERR_JWKS_INVALID";class Wt extends se{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Wt.code="ERR_JWKS_NO_MATCHING_KEY";class Hr extends se{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Hr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Kr extends se{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}Kr.code="ERR_JWKS_TIMEOUT";class Gr extends se{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Gr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function rt(s,e){return s.name===e}function Ht(s){return parseInt(s.name.slice(4),10)}function vi(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ei(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function Ai(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!rt(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Ht(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!rt(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Ht(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!rt(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Ht(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!rt(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!rt(s.algorithm,"ECDSA"))throw we("ECDSA");const t=vi(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ei(s,r)}function Vr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const qr=(s,...e)=>Vr("Key must be ",s,...e);function zr(s,e,...r){return Vr(`Key for the ${s} algorithm must be `,e,...r)}const Jr=s=>Ur(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",xt=["CryptoKey"],Ii=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function Ri(s){return typeof s=="object"&&s!==null}function Se(s){if(!Ri(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const Ti=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ve(s){return Se(s)&&typeof s.kty=="string"}function ki(s){return s.kty!=="oct"&&typeof s.d=="string"}function Ni(s){return s.kty!=="oct"&&typeof s.d>"u"}function Ci(s){return Ve(s)&&s.kty==="oct"&&typeof s.k=="string"}function Oi(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const Yr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=Oi(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,$t.subtle.importKey("jwk",n,...t)},jr=s=>ke(s);let qe,ze;const Xr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",wt=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await Yr({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},Pi={normalizePublicKey:(s,e)=>{if(Xr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?jr(r.k):(ze||(ze=new WeakMap),wt(ze,s,r,e))}return Ve(s)?s.k?ke(s.k):(ze||(ze=new WeakMap),wt(ze,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Xr(s)){let r=s.export({format:"jwk"});return r.k?jr(r.k):(qe||(qe=new WeakMap),wt(qe,s,r,e))}return Ve(s)?s.k?ke(s.k):(qe||(qe=new WeakMap),wt(qe,s,s,e,!0)):s}};async function Zr(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return ke(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Yr({...s,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const Je=s=>s==null?void 0:s[Symbol.toStringTag],Kt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},Di=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ve(e)){if(Ci(e)&&Kt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Jr(e))throw new TypeError(zr(s,e,...xt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Je(e)} instances for symmetric algorithms must be of type "secret"`)}},Li=(s,e,r,t)=>{if(t&&Ve(e))switch(r){case"sign":if(ki(e)&&Kt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Ni(e)&&Kt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Jr(e))throw new TypeError(zr(s,e,...xt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Je(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${Je(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${Je(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${Je(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${Je(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Qr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Di(e,r,t,s):Li(e,r,t,s)}Qr.bind(void 0,!1);const es=Qr.bind(void 0,!0);function Bi(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const Mi=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function $i(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function Fi(s,e,r){if(e=await Pi.normalizePublicKey(e,s),Ur(e))return Ai(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(qr(e,...xt));return $t.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(qr(e,...xt,"Uint8Array","JSON Web Key"))}const Ui=async(s,e,r,t)=>{const n=await Fi(s,e,"verify");Ti(s,n);const i=$i(s,n.algorithm);try{return await $t.subtle.verify(i,n,r,t)}catch{return!1}};async function Wi(s,e,r){if(!Se(s))throw new te("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new te('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new te("JWS Protected Header incorrect type");if(s.payload===void 0)throw new te("JWS Payload missing");if(typeof s.signature!="string")throw new te("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new te("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const g=ke(s.protected);t=JSON.parse(tt.decode(g))}catch{throw new te("JWS Protected Header is invalid")}if(!Ii(t,s.header))throw new te("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=Bi(te,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new te('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new te('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&Mi("algorithms",r.algorithms);if(c&&!c.has(a))throw new Wr('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new te("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new te("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,es(a,e,"verify"),Ve(e)&&(e=await Zr(e,a))):es(a,e,"verify");const u=wi(gt.encode(s.protected??""),gt.encode("."),typeof s.payload=="string"?gt.encode(s.payload):s.payload);let p;try{p=ke(s.signature)}catch{throw new te("Failed to base64url decode the signature")}if(!await Ui(a,e,p,u))throw new Gr;let x;if(o)try{x=ke(s.payload)}catch{throw new te("Failed to base64url decode the payload")}else typeof s.payload=="string"?x=gt.encode(s.payload):x=s.payload;const w={payload:x};return s.protected!==void 0&&(w.protectedHeader=t),s.header!==void 0&&(w.unprotectedHeader=s.header),l?{...w,key:e}:w}async function Hi(s,e,r){if(s instanceof Uint8Array&&(s=tt.decode(s)),typeof s!="string")throw new te("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new te("Invalid Compact JWS");const a=await Wi({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Ki=s=>Math.floor(s.getTime()/1e3),ts=60,rs=ts*60,Gt=rs*24,Gi=Gt*7,Vi=Gt*365.25,qi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,ss=s=>{const e=qi.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*ts);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*rs);break;case"day":case"days":case"d":n=Math.round(r*Gt);break;case"week":case"weeks":case"w":n=Math.round(r*Gi);break;default:n=Math.round(r*Vi);break}return e[1]==="-"||e[4]==="ago"?-n:n},ns=s=>s.toLowerCase().replace(/^application\//,""),zi=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Ji=(s,e,r={})=>{let t;try{t=JSON.parse(tt.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||ns(s.typ)!==ns(n)))throw new pe('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const w of new Set(u.reverse()))if(!(w in t))throw new pe(`missing required "${w}" claim`,t,w,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new pe('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new pe('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!zi(t.aud,typeof c=="string"?[c]:c))throw new pe('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=ss(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=r,x=Ki(_||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new pe('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new pe('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>x+p)throw new pe('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new pe('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=x-p)throw new Ft('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const w=x-t.iat,g=typeof l=="number"?l:ss(l);if(w-p>g)throw new Ft('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(w<0-p)throw new pe('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Yi(s,e,r){var o;const t=await Hi(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:Ji(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function ji(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function Xi(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Zi)}function Zi(s){return Se(s)}function is(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Qi{constructor(e){if(this._cached=new WeakMap,!Xi(e))throw new Ut("JSON Web Key Set malformed");this._jwks=is(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=ji(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Wt;if(c!==1){const l=new Hr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await os(u,p,t)}catch{}},l}return os(this._cached,a,t)}}async function os(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Zr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new Ut("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function as(s){const e=new Qi(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>is(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const eo=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new Kr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new se("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new se("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function to(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Vt;(typeof navigator>"u"||!((bn=(Ct=navigator.userAgent)==null?void 0:Ct.startsWith)!=null&&bn.call(Ct,"Mozilla/5.0 ")))&&(Vt="jose/v5.10.0");const qt=Symbol();function ro(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class so{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[qt])!==void 0&&(this._cache=r==null?void 0:r[qt],ro(r==null?void 0:r[qt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=as(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Wt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&to()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Vt&&!e.has("User-Agent")&&(e.set("User-Agent",Vt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=eo(this._url,this._timeoutDuration,this._options).then(r=>{this._local=as(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function no(s,e){const r=new so(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const io=ke;function oo(s){if(typeof s!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=io(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(tt.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function zt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function Z(s,e,r=""){const t=zt(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 cs(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Ye(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 ls(s,e){Z(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 ao(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Jt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const co=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function uo(s){for(let e=0;e<s.length;e++)s[e]=lo(s[e]);return s}const ds=co?s=>s:uo,us=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ho=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function st(s){if(Z(s),us)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=ho[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function hs(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function mt(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(us)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=hs(s.charCodeAt(i)),a=hs(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 Ne(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];Z(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 ps(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 fs(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 po=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function fo(s,e,r){return s&e^~s&r}function _o(s,e,r){return s&e^s&r^e&r}class go{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=Jt(this.buffer)}update(e){Ye(this),Z(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=Jt(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){Ye(this),ls(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,je(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=Jt(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 Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),yt=BigInt(2**32-1),_s=BigInt(32);function xo(s,e=!1){return e?{h:Number(s&yt),l:Number(s>>_s&yt)}:{h:Number(s>>_s&yt)|0,l:Number(s&yt)|0}}function wo(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}=xo(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const mo=(s,e,r)=>s<<r|e>>>32-r,yo=(s,e,r)=>e<<r|s>>>32-r,bo=(s,e,r)=>e<<r-32|s>>>64-r,So=(s,e,r)=>s<<r-32|e>>>64-r,vo=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]),Oe=new Uint32Array(64);class Eo extends go{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)Oe[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const _=Oe[p-15],x=Oe[p-2],w=me(_,7)^me(_,18)^_>>>3,g=me(x,17)^me(x,19)^x>>>10;Oe[p]=g+Oe[p-7]+w+Oe[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 _=me(a,6)^me(a,11)^me(a,25),x=u+_+fo(a,c,l)+vo[p]+Oe[p]|0,g=(me(t,2)^me(t,13)^me(t,22))+_o(t,n,i)|0;u=l,l=c,c=a,a=o+x|0,o=i,i=n,n=t,t=x+g|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(){je(Oe)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}}class Ao extends Eo{constructor(){super(32);P(this,"A",Ce[0]|0);P(this,"B",Ce[1]|0);P(this,"C",Ce[2]|0);P(this,"D",Ce[3]|0);P(this,"E",Ce[4]|0);P(this,"F",Ce[5]|0);P(this,"G",Ce[6]|0);P(this,"H",Ce[7]|0)}}const Io=ps(()=>new Ao,po(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yt=BigInt(0),jt=BigInt(1);function bt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function gs(s){if(typeof s=="bigint"){if(!Et(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function St(s){const e=gs(s).toString(16);return e.length&1?"0"+e:e}function xs(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Yt:BigInt("0x"+s)}function vt(s){return xs(st(s))}function ws(s){return xs(st(Ro(Z(s)).reverse()))}function Xt(s,e){ve(e),s=gs(s);const r=mt(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function ms(s,e){return Xt(s,e).reverse()}function Ro(s){return Uint8Array.from(s)}const Et=s=>typeof s=="bigint"&&Yt<=s;function To(s,e,r){return Et(s)&&Et(e)&&Et(r)&&e<=s&&s<r}function ko(s,e,r,t){if(!To(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function No(s){let e;for(e=0;s>Yt;s>>=jt,e+=1);return e}const Zt=s=>(jt<<BigInt(s))-jt;function Co(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=m=>new Uint8Array(m),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},_=(...m)=>r(l,Ne(c,...m)),x=(m=n)=>{l=_(i,m),c=_(),m.length!==0&&(l=_(o,m),c=_())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let m=0;const E=[];for(;m<e;){c=_();const I=c.slice();E.push(I),m+=c.length}return Ne(...E)};return(m,E)=>{p(),x(m);let I;for(;!(I=E(w()));)x();return p(),I}}function Qt(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 ys(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 ae=BigInt(0),ie=BigInt(1),De=BigInt(2),bs=BigInt(3),Ss=BigInt(4),vs=BigInt(5),Oo=BigInt(7),Es=BigInt(8),Po=BigInt(9),As=BigInt(16);function fe(s,e){const r=s%e;return r>=ae?r:e+r}function le(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function Is(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=fe(s,e),t=e,n=ae,i=ie;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==ie)throw new Error("invert: does not exist");return fe(n,e)}function er(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Rs(s,e){const r=(s.ORDER+ie)/Ss,t=s.pow(e,r);return er(s,t,e),t}function Do(s,e){const r=(s.ORDER-vs)/Es,t=s.mul(e,De),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,De),n),a=s.mul(i,s.sub(o,s.ONE));return er(s,a,e),a}function Lo(s){const e=At(s),r=Ts(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+Oo)/As;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),_=a.mul(l,i),x=a.eql(a.sqr(u),c),w=a.eql(a.sqr(p),c);l=a.cmov(l,u,x),u=a.cmov(_,p,w);const g=a.eql(a.sqr(u),c),m=a.cmov(l,u,g);return er(a,m,c),m}}function Ts(s){if(s<bs)throw new Error("sqrt is not defined for small field");let e=s-ie,r=0;for(;e%De===ae;)e/=De,r++;let t=De;const n=At(s);for(;Ns(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Rs;let i=n.pow(t,e);const o=(e+ie)/De;return function(c,l){if(c.is0(l))return l;if(Ns(c,l)!==1)throw new Error("Cannot find square root");let u=r,p=c.mul(c.ONE,i),_=c.pow(l,e),x=c.pow(l,o);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let w=1,g=c.sqr(_);for(;!c.eql(g,c.ONE);)if(w++,g=c.sqr(g),w===u)throw new Error("Cannot find square root");const m=ie<<BigInt(u-w-1),E=c.pow(p,m);u=w,p=c.sqr(E),_=c.mul(_,p),x=c.mul(x,E)}return x}}function Bo(s){return s%Ss===bs?Rs:s%Es===vs?Do:s%As===Po?Lo(s):Ts(s)}const Mo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $o(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Mo.reduce((t,n)=>(t[n]="function",t),e);return Qt(s,r),s}function Fo(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===ie)return e;let t=s.ONE,n=e;for(;r>ae;)r&ie&&(t=s.mul(t,n)),n=s.sqr(n),r>>=ie;return t}function ks(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 Ns(s,e){const r=(s.ORDER-ie)/De,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 Uo(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Wo{constructor(e,r={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ae);P(this,"ONE",ie);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=ae)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}=Uo(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 fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ie)===ie}neg(e){return fe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return fe(e*e,this.ORDER)}add(e,r){return fe(e+r,this.ORDER)}sub(e,r){return fe(e-r,this.ORDER)}mul(e,r){return fe(e*r,this.ORDER)}pow(e,r){return Fo(this,e,r)}div(e,r){return fe(e*Is(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 Is(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Bo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ms(e,this.BYTES):Xt(e,this.BYTES)}fromBytes(e,r=!1){Z(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?ws(e):vt(e);if(a&&(c=fe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ks(this,e)}cmov(e,r,t){return t?r:e}}function At(s,e={}){return new Wo(s,e)}function Cs(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 Os(s){const e=Cs(s);return e+Math.ceil(e/2)}function Ho(s,e,r=!1){Z(s);const t=s.length,n=Cs(e),i=Os(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?ws(s):vt(s),a=fe(o,e-ie)+ie;return r?ms(a,n):Xt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Xe=BigInt(0),Le=BigInt(1);function It(s,e){const r=e.negate();return s?r:e}function Ps(s,e){const r=ks(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Ds(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function tr(s,e){Ds(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Zt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function Ls(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+=Le);const l=e*t,u=l+Math.abs(a)-1,p=a===0,_=a<0,x=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:_,isNegF:x,offsetF:l}}const rr=new WeakMap,Bs=new WeakMap;function sr(s){return Bs.get(s)||1}function Ms(s){if(s!==Xe)throw new Error("invalid wNAF")}class Ko{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>Xe;)r&Le&&(t=t.add(n)),n=n.double(),r>>=Le;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=tr(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=tr(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:_,offsetF:x}=Ls(t,a,o);t=c,u?i=i.add(It(_,r[x])):n=n.add(It(p,r[l]))}return Ms(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=tr(e,this.bits);for(let o=0;o<i.windows&&t!==Xe;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Ls(t,o,i);if(t=a,!l){const p=r[c];n=n.add(u?p.negate():p)}}return Ms(t),n}getPrecomputes(e,r,t){let n=rr.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),rr.set(r,n))),n}cached(e,r,t){const n=sr(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=sr(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Ds(r,this.bits),Bs.set(e,r),rr.delete(e)}hasCache(e){return sr(e)!==1}}function Go(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Xe||t>Xe;)r&Le&&(i=i.add(n)),t&Le&&(o=o.add(n)),n=n.double(),r>>=Le,t>>=Le;return{p1:i,p2:o}}function $s(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $o(e),e}else return At(s,{isLE:r})}function Vo(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>Xe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=$s(e.p,r.Fp,t),i=$s(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 qo(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Fs{constructor(e,r){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(cs(e),Z(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),je(n)}update(e){return Ye(this),this.iHash.update(e),this}digestInto(e){Ye(this),Z(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 Us=(s,e,r)=>new Fs(s,e).update(r).digest();Us.create=(s,e)=>new Fs(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ws=(s,e)=>(s+(s>=0?e:-e)/Hs)/e;function zo(s,e,r){const[[t,n],[i,o]]=e,a=Ws(o*s,r),c=Ws(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const p=l<Ae,_=u<Ae;p&&(l=-l),_&&(u=-u);const x=Zt(Math.ceil(No(r)/2))+Ze;if(l<Ae||l>=x||u<Ae||u>=x)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:_,k2:u}}function nr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function ir(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return bt(r.lowS,"lowS"),bt(r.prehash,"prehash"),r.format!==void 0&&nr(r.format),r}class Jo extends Error{constructor(e=""){super(e)}}const Pe={Err:Jo,_tlv:{encode:(s,e)=>{const{Err:r}=Pe;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=St(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?St(n.length/2|128):"";return St(s)+i+n+e},decode(s,e){const{Err:r}=Pe;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}=Pe;if(s<Ae)throw new e("integer: negative integers are not allowed");let r=St(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}=Pe;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 vt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Pe,n=Z(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}=Pe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Ze=BigInt(1),Hs=BigInt(2),Rt=BigInt(3),Yo=BigInt(4);function jo(s,e={}){const r=Vo("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Qt(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=Gs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(U,y,b){const{x:T,y:C}=y.toAffine(),$=t.toBytes(T);if(bt(b,"isCompressed"),b){u();const B=!t.isOdd(C);return Ne(Ks(B),$)}else return Ne(Uint8Array.of(4),$,t.toBytes(C))}function _(U){Z(U,void 0,"Point");const{publicKey:y,publicKeyUncompressed:b}=l,T=U.length,C=U[0],$=U.subarray(1);if(T===y&&(C===2||C===3)){const B=t.fromBytes($);if(!t.isValid(B))throw new Error("bad point: is not on curve, wrong x");const M=g(B);let O;try{O=t.sqrt(M)}catch(A){const k=A instanceof Error?": "+A.message:"";throw new Error("bad point: is not on curve, sqrt error"+k)}u();const K=t.isOdd(O);return(C&1)===1!==K&&(O=t.neg(O)),{x:B,y:O}}else if(T===b&&C===4){const B=t.BYTES,M=t.fromBytes($.subarray(0,B)),O=t.fromBytes($.subarray(B,B*2));if(!m(M,O))throw new Error("bad point: is not on curve");return{x:M,y:O}}else throw new Error(`bad point: got length ${T}, expected compressed=${y} or uncompressed=${b}`)}const x=e.toBytes||p,w=e.fromBytes||_;function g(U){const y=t.sqr(U),b=t.mul(y,U);return t.add(t.add(b,t.mul(U,i.a)),i.b)}function m(U,y){const b=t.sqr(y),T=g(U);return t.eql(b,T)}if(!m(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(i.a,Rt),Yo),I=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(E,I)))throw new Error("bad curve params: a or b");function N(U,y,b=!1){if(!t.isValid(y)||b&&t.is0(y))throw new Error(`bad point coordinate ${U}`);return y}function L(U){if(!(U instanceof G))throw new Error("Weierstrass Point expected")}function W(U){if(!c||!c.basises)throw new Error("no endo");return zo(U,c.basises,n.ORDER)}const z=ys((U,y)=>{const{X:b,Y:T,Z:C}=U;if(t.eql(C,t.ONE))return{x:b,y:T};const $=U.is0();y==null&&(y=$?t.ONE:t.inv(C));const B=t.mul(b,y),M=t.mul(T,y),O=t.mul(C,y);if($)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),Q=ys(U=>{if(U.is0()){if(e.allowInfinityPoint&&!t.is0(U.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:b}=U.toAffine();if(!t.isValid(y)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!m(y,b))throw new Error("bad point: equation left != right");if(!U.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Y(U,y,b,T,C){return b=new G(t.mul(b.X,U),b.Y,b.Z),y=It(T,y),b=It(C,b),y.add(b)}const F=class F{constructor(y,b,T){P(this,"X");P(this,"Y");P(this,"Z");this.X=N("x",y),this.Y=N("y",b,!0),this.Z=N("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){const{x:b,y:T}=y||{};if(!y||!t.isValid(b)||!t.isValid(T))throw new Error("invalid affine point");if(y instanceof F)throw new Error("projective point not allowed");return t.is0(b)&&t.is0(T)?F.ZERO:new F(b,T,t.ONE)}static fromBytes(y){const b=F.fromAffine(w(Z(y,void 0,"point")));return b.assertValidity(),b}static fromHex(y){return F.fromBytes(mt(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,b=!0){return D.createCache(this,y),b||this.multiply(Rt),this}assertValidity(){Q(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:b,Y:T,Z:C}=this,{X:$,Y:B,Z:M}=y,O=t.eql(t.mul(b,M),t.mul($,C)),K=t.eql(t.mul(T,M),t.mul(B,C));return O&&K}negate(){return new F(this.X,t.neg(this.Y),this.Z)}double(){const{a:y,b}=i,T=t.mul(b,Rt),{X:C,Y:$,Z:B}=this;let M=t.ZERO,O=t.ZERO,K=t.ZERO,S=t.mul(C,C),A=t.mul($,$),k=t.mul(B,B),R=t.mul(C,$);return R=t.add(R,R),K=t.mul(C,B),K=t.add(K,K),M=t.mul(y,K),O=t.mul(T,k),O=t.add(M,O),M=t.sub(A,O),O=t.add(A,O),O=t.mul(M,O),M=t.mul(R,M),K=t.mul(T,K),k=t.mul(y,k),R=t.sub(S,k),R=t.mul(y,R),R=t.add(R,K),K=t.add(S,S),S=t.add(K,S),S=t.add(S,k),S=t.mul(S,R),O=t.add(O,S),k=t.mul($,B),k=t.add(k,k),S=t.mul(k,R),M=t.sub(M,S),K=t.mul(k,A),K=t.add(K,K),K=t.add(K,K),new F(M,O,K)}add(y){L(y);const{X:b,Y:T,Z:C}=this,{X:$,Y:B,Z:M}=y;let O=t.ZERO,K=t.ZERO,S=t.ZERO;const A=i.a,k=t.mul(i.b,Rt);let R=t.mul(b,$),H=t.mul(T,B),V=t.mul(C,M),j=t.add(b,T),q=t.add($,B);j=t.mul(j,q),q=t.add(R,H),j=t.sub(j,q),q=t.add(b,C);let X=t.add($,M);return q=t.mul(q,X),X=t.add(R,V),q=t.sub(q,X),X=t.add(T,C),O=t.add(B,M),X=t.mul(X,O),O=t.add(H,V),X=t.sub(X,O),S=t.mul(A,q),O=t.mul(k,V),S=t.add(O,S),O=t.sub(H,S),S=t.add(H,S),K=t.mul(O,S),H=t.add(R,R),H=t.add(H,R),V=t.mul(A,V),q=t.mul(k,q),H=t.add(H,V),V=t.sub(R,V),V=t.mul(A,V),q=t.add(q,V),R=t.mul(H,q),K=t.add(K,R),R=t.mul(X,q),O=t.mul(j,O),O=t.sub(O,R),R=t.mul(j,H),S=t.mul(X,S),S=t.add(S,R),new F(O,K,S)}subtract(y){return this.add(y.negate())}is0(){return this.equals(F.ZERO)}multiply(y){const{endo:b}=e;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let T,C;const $=B=>D.cached(this,B,M=>Ps(F,M));if(b){const{k1neg:B,k1:M,k2neg:O,k2:K}=W(y),{p:S,f:A}=$(M),{p:k,f:R}=$(K);C=A.add(R),T=Y(b.beta,S,k,B,O)}else{const{p:B,f:M}=$(y);T=B,C=M}return Ps(F,[T,C])[0]}multiplyUnsafe(y){const{endo:b}=e,T=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Ae||T.is0())return F.ZERO;if(y===Ze)return T;if(D.hasCache(this))return this.multiply(y);if(b){const{k1neg:C,k1:$,k2neg:B,k2:M}=W(y),{p1:O,p2:K}=Go(F,T,$,M);return Y(b.beta,O,K,C,B)}else return D.unsafe(T,y)}toAffine(y){return z(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Ze?!0:y?y(F,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Ze?this:y?y(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return bt(y,"isCompressed"),this.assertValidity(),x(F,this,y)}toHex(y=!0){return st(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(F,"BASE",new F(i.Gx,i.Gy,t.ONE)),P(F,"ZERO",new F(t.ZERO,t.ONE,t.ZERO)),P(F,"Fp",t),P(F,"Fn",n);let G=F;const ne=n.BITS,D=new Ko(G,e.endo?Math.ceil(ne/2):ne);return G.BASE.precompute(8),G}function Ks(s){return Uint8Array.of(s?2:3)}function Gs(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Xo(s,e={}){const{Fn:r}=s,t=e.randomBytes||fs,n=Object.assign(Gs(s.Fp,r),{seed:Os(r.ORDER)});function i(x){try{const w=r.fromBytes(x);return r.isValidNot0(w)}catch{return!1}}function o(x,w){const{publicKey:g,publicKeyUncompressed:m}=n;try{const E=x.length;return w===!0&&E!==g||w===!1&&E!==m?!1:!!s.fromBytes(x)}catch{return!1}}function a(x=t(n.seed)){return Ho(Z(x,n.seed,"seed"),r.ORDER)}function c(x,w=!0){return s.BASE.multiply(r.fromBytes(x)).toBytes(w)}function l(x){const{secretKey:w,publicKey:g,publicKeyUncompressed:m}=n;if(!zt(x)||"_lengths"in r&&r._lengths||w===g)return;const E=Z(x,void 0,"key").length;return E===g||E===m}function u(x,w,g=!0){if(l(x)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const m=r.fromBytes(x);return s.fromBytes(w).multiply(m).toBytes(g)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=qo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:s,utils:p,lengths:n})}function Zo(s,e,r={}){cs(e),Qt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||fs,n=r.hmac||((y,b)=>Us(e,y,b)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:_,lengths:x}=Xo(s,r),w={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},g=a*Hs<i.ORDER;function m(y){const b=a>>Ze;return y>b}function E(y,b){if(!o.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function I(){if(g)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function N(y,b){nr(b);const T=x.signature,C=b==="compact"?T:b==="recovered"?T+1:void 0;return Z(y,C)}class L{constructor(b,T,C){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=E("r",b),this.s=E("s",T),C!=null){if(I(),![0,1,2,3].includes(C))throw new Error("invalid recovery id");this.recovery=C}Object.freeze(this)}static fromBytes(b,T=w.format){N(b,T);let C;if(T==="der"){const{r:O,s:K}=Pe.toSig(Z(b));return new L(O,K)}T==="recovered"&&(C=b[0],T="compact",b=b.subarray(1));const $=x.signature/2,B=b.subarray(0,$),M=b.subarray($,$*2);return new L(o.fromBytes(B),o.fromBytes(M),C)}static fromHex(b,T){return this.fromBytes(mt(b),T)}assertRecovery(){const{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new L(this.r,this.s,b)}recoverPublicKey(b){const{r:T,s:C}=this,$=this.assertRecovery(),B=$===2||$===3?T+a:T;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes(B),O=s.fromBytes(Ne(Ks(($&1)===0),M)),K=o.inv(B),S=z(Z(b,void 0,"msgHash")),A=o.create(-S*K),k=o.create(C*K),R=s.BASE.multiplyUnsafe(A).add(O.multiplyUnsafe(k));if(R.is0())throw new Error("invalid recovery: point at infinify");return R.assertValidity(),R}hasHighS(){return m(this.s)}toBytes(b=w.format){if(nr(b),b==="der")return mt(Pe.hexFromSig(this));const{r:T,s:C}=this,$=o.toBytes(T),B=o.toBytes(C);return b==="recovered"?(I(),Ne(Uint8Array.of(this.assertRecovery()),$,B)):Ne($,B)}toHex(b){return st(this.toBytes(b))}}const W=r.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const T=vt(b),C=b.length*8-c;return C>0?T>>BigInt(C):T},z=r.bits2int_modN||function(b){return o.create(W(b))},Q=Zt(c);function Y(y){return ko("num < 2^"+c,y,Ae,Q),o.toBytes(y)}function G(y,b){return Z(y,void 0,"message"),b?Z(e(y),void 0,"prehashed message"):y}function ne(y,b,T){const{lowS:C,prehash:$,extraEntropy:B}=ir(T,w);y=G(y,$);const M=z(y),O=o.fromBytes(b);if(!o.isValidNot0(O))throw new Error("invalid private key");const K=[Y(O),Y(M)];if(B!=null&&B!==!1){const R=B===!0?t(x.secretKey):B;K.push(Z(R,void 0,"extraEntropy"))}const S=Ne(...K),A=M;function k(R){const H=W(R);if(!o.isValidNot0(H))return;const V=o.inv(H),j=s.BASE.multiply(H).toAffine(),q=o.create(j.x);if(q===Ae)return;const X=o.create(V*o.create(A+q*O));if(X===Ae)return;let Ue=(j.x===q?0:2)|Number(j.y&Ze),Sn=X;return C&&m(X)&&(Sn=o.neg(X),Ue^=1),new L(q,Sn,g?void 0:Ue)}return{seed:S,k2sig:k}}function D(y,b,T={}){const{seed:C,k2sig:$}=ne(y,b,T);return Co(e.outputLen,o.BYTES,n)(C,$).toBytes(T.format)}function F(y,b,T,C={}){const{lowS:$,prehash:B,format:M}=ir(C,w);if(T=Z(T,void 0,"publicKey"),b=G(b,B),!zt(y)){const O=y instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}N(y,M);try{const O=L.fromBytes(y,M),K=s.fromBytes(T);if($&&O.hasHighS())return!1;const{r:S,s:A}=O,k=z(b),R=o.inv(A),H=o.create(k*R),V=o.create(S*R),j=s.BASE.multiplyUnsafe(H).add(K.multiplyUnsafe(V));return j.is0()?!1:o.create(j.x)===S}catch{return!1}}function U(y,b,T={}){const{prehash:C}=ir(T,w);return b=G(b,C),L.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:_,lengths:x,Point:s,sign:D,verify:F,recoverPublicKey:U,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const or={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Qo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Vs=BigInt(2);function ea(s){const e=or.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=le(u,r,e)*u%e,_=le(p,r,e)*u%e,x=le(_,Vs,e)*l%e,w=le(x,n,e)*x%e,g=le(w,i,e)*w%e,m=le(g,a,e)*g%e,E=le(m,c,e)*m%e,I=le(E,a,e)*g%e,N=le(I,r,e)*u%e,L=le(N,o,e)*w%e,W=le(L,t,e)*l%e,z=le(W,Vs,e);if(!ar.eql(ar.sqr(z),s))throw new Error("Cannot find square root");return z}const ar=At(or.p,{sqrt:ea}),ta=Zo(jo(or,{Fp:ar,endo:Qo}),Io),ra=BigInt(0),nt=BigInt(1),sa=BigInt(2),na=BigInt(7),ia=BigInt(256),oa=BigInt(113),qs=[],zs=[],Js=[];for(let s=0,e=nt,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],qs.push(2*(5*t+r)),zs.push((s+1)*(s+2)/2%64);let n=ra;for(let i=0;i<7;i++)e=(e<<nt^(e>>na)*oa)%ia,e&sa&&(n^=nt<<(nt<<BigInt(i))-nt);Js.push(n)}const Ys=wo(Js,!0),aa=Ys[0],ca=Ys[1],js=(s,e,r)=>r>32?bo(s,e,r):mo(s,e,r),Xs=(s,e,r)=>r>32?So(s,e,r):yo(s,e,r);function la(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=js(l,u,1)^r[a],_=Xs(l,u,1)^r[a+1];for(let x=0;x<50;x+=10)s[o+x]^=p,s[o+x+1]^=_}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=zs[o],c=js(n,i,a),l=Xs(n,i,a),u=qs[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]^=aa[t],s[1]^=ca[t]}je(r)}class cr{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,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ao(this.state)}clone(){return this._cloneInto()}keccak(){ds(this.state32),la(this.state32,this.rounds),ds(this.state32),this.posOut=0,this.pos=0}update(e){Ye(this),Z(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)!==0&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ye(this,!1),Z(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 ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ls(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,je(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new cr(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 Zs=((s,e,r,t={})=>ps(()=>new cr(e,s,r),t))(1,136,32),da=60;class ua{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=no(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+da<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 Yi(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 oo(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=Zs(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=ha(a),l=c.slice(0,32),u=c.slice(32,64),p=c[64],_=p>=27?p-27:p,g=new ta.Signature(Qs(l),Qs(u)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),m=Zs(g);return"0x"+st(m.slice(12))}}function ha(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 Qs(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const pa=5e3;class fa{constructor(e,r){this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyInFlight=null,this.keyFailedAt=0,this.required=!1,this.adapterConfig=e,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async seal(e){if(!e)return e;const r=this.required;if(!r&&this.hasFreshFailure())return e;try{const{version:t,key:n}=await this.currentKey(),i=await _a(n,e);return`${t}.${ga(i)}`}catch(t){if(r)throw this.keyFailedAt=Date.now(),t instanceof f?t:new f(h.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(t)});return this.keyFailedAt=Date.now(),d.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(Ir/1e3)}초 후 재확인)`),e}}invalidate(){d.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(d.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.currentKey().then(()=>{},()=>{})}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<Ir}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<kn?{version:this.cachedVersion,key:this.cachedKey}:this.keyInFlight?this.keyInFlight:(this.keyInFlight=this.fetchAndImportKey().then(e=>(this.cachedVersion=e.version,this.cachedKey=e.key,this.cachedAt=Date.now(),this.keyFailedAt=0,d.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=en();if(!e)throw new f(h.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다. HTTPS 환경에서 다시 시도해 주세요.");const r=await this.transport.request({url:`${this.baseUrl}/pin-key`,method:"GET",headers:{"X-Project-Id":this.adapterConfig.projectId},timeoutMs:pa}),t=ya(r.data);if(!(t!=null&&t.keyVersion)||!(t!=null&&t.publicKey))throw new f(h.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const n=wa(t.publicKey),i=await e.importKey("spki",ma(n),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:t.keyVersion,key:i}}}async function _a(s,e){const r=en();if(!r)throw new f(h.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const t=await r.encrypt({name:"RSA-OAEP"},s,new TextEncoder().encode(e));return new Uint8Array(t)}function en(){const s=globalThis.crypto;return(s==null?void 0:s.subtle)??null}function ga(s){return xa(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const it="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function xa(s){let e="";for(let r=0;r<s.length;r+=3){const t=s[r],n=s[r+1],i=s[r+2];e+=it[t>>2],e+=it[(t&3)<<4|(n??0)>>4],e+=n===void 0?"=":it[(n&15)<<2|(i??0)>>6],e+=i===void 0?"=":it[i&63]}return e}function wa(s){const e=s.replace(/-----BEGIN [A-Z ]+-----/g,"").replace(/-----END [A-Z ]+-----/g,"").replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?e:e+"=".repeat(4-e.length%4),t=[];for(let n=0;n<r.length;n+=4){const i=[0,1,2,3].map(o=>{const a=r[n+o];if(a==="="||a===void 0)return-1;const c=it.indexOf(a);if(c===-1)throw new f(h.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return c});t.push((i[0]&63)<<2|(i[1]&63)>>4),i[2]!==-1&&t.push((i[1]&15)<<4|(i[2]&63)>>2),i[3]!==-1&&t.push((i[2]&3)<<6|i[3]&63)}return new Uint8Array(t)}function ma(s){const e=new Uint8Array(s.length);return e.set(s),e.buffer}function ya(s){if(!s||typeof s!="object")return null;const e=s;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new f(h.PIN_ENCRYPTION_FAILED,`pin-key 조회 실패 (${e.code}): ${String(e.message??e.data??"")}`);const r=e.data;if(r&&typeof r=="object")return r}return typeof e.keyVersion=="string"&&typeof e.publicKey=="string"?e:null}const ba=3e4,Sa=1e3;class va{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,Sa*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??ba);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 Ea=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function lr(){return typeof window>"u"?void 0:window}function Aa(){const s=lr();return s==null?void 0:s.__crossx}function Ia(s){return s==="ios"||s==="android"?s:null}function dr(){const s=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(s)?"android":/iPhone|iPad|iPod|Macintosh/i.test(s)?"ios":null}function Ra(s,e){const r=o=>o.split(/[^\d]+/).filter(a=>a!=="").map(a=>Number.parseInt(a,10)),t=r(s),n=r(e),i=Math.max(t.length,n.length);for(let o=0;o<i;o+=1){const a=(t[o]??0)-(n[o]??0);if(a!==0)return a}return 0}function Ta(){const s=lr();if(!s)return!1;const e=s.__crossxRNBridge;return e!=null&&e.isInstalled?!0:s.__CROSSX_BRIDGE_INITIALIZED__===!0||s.__CROSSX_RN_BRIDGE_READY__===!0}function tn(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of Ea){const r=e.exec(s);if(r)return r[1]??null}}function ot(){const s=Aa();if(s!=null&&s.browser)return{version:s.version??null,platform:Ia(s.platform)??dr(),detectedBy:"marker"};if(Ta())return{version:tn()??null,platform:dr(),detectedBy:"bridge"};const e=tn();return e!==void 0?{version:e,platform:dr(),detectedBy:"user-agent"}:null}function ka(){return ot()!==null}function Na(s=3e3){const e=ot();return e?Promise.resolve(e):lr()?new Promise(r=>{const t=Date.now(),n=setInterval(()=>{const i=ot();if(i){clearInterval(n),r(i);return}Date.now()-t>=s&&(clearInterval(n),r(null))},50)}):Promise.resolve(null)}const Ca=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io","https://one-wallet-oauth.onechain.nexus","https://stg-one-wallet-oauth.onechain.nexus","https://dev-one-wallet-oauth.onechain.nexus"]),Oa="crossx://oauth-callback",Pa="2.3.2";function Da(s){return s.platform!=="ios"?!1:s.version?Ra(s.version,Pa)<=0:!0}class Be{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(d.log("[CROSSx] OAuth 대기 중단 —",e),r(e))}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=Be.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 Be.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=Be.generateRandom16Hex(),l=Be.generateRandom16Hex(),u=ot();let p=e.authUrl;u&&e.legacyAuthUrl&&Da(u)&&(p=e.legacyAuthUrl,d.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:u.version??"(unknown)",detectedBy:u.detectedBy,authUrlBase:e.legacyAuthUrl}));const _=p.includes("?")?"&":"?",x=encodeURIComponent(window.location.origin);let w=`${p}${_}state=${c}&nonce=${l}&origin=${x}`;u&&!w.includes("redirectUrl=")&&(w+=`&redirectUrl=${encodeURIComponent(Oa)}`,d.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:u.detectedBy,appVersion:u.version??"(unknown)",platform:u.platform??"(unknown)"})),d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:p});const g=window.open(w,u?"_blank":"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const m=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),Q(),t(new Error("Authentication timeout"))},300*1e3),E=10,I=30;let N=0,L=null;const W=()=>{clearInterval(z),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+I+"초간 대기합니다"),L=setTimeout(()=>{Q(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},I*1e3)},z=setInterval(()=>{N++;try{if(!g.closed)return;if(!!u){Q(),t(new f(h.USER_REJECTED,"로그인이 취소되었습니다"));return}const ne=typeof document<"u"&&document.hasFocus();N<=E&&!ne?W():(Q(),t(new f(h.USER_REJECTED,"로그인이 취소되었습니다")))}catch{W()}},1e3),Q=()=>{this.abortPending=null,clearTimeout(m),clearInterval(z),L&&clearTimeout(L),window.removeEventListener("message",Y)},Y=G=>{if(!Ca.has(G.origin))return;Q();const ne=typeof G.data.status=="string",D=ne?G.data.data??{}:G.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:ne?"wrapped":"flat",status:ne?G.data.status:"(flat)"});const F=(D==null?void 0:D.state)??G.data.state;if(!F||F!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ne&&G.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",D==null?void 0:D.error),t(new Error((D==null?void 0:D.error)||"Authentication failed"));return}if(!ne&&(D!=null&&D.error)){d.error("[CROSSx] OAuth 실패:",D.error),t(new Error(D.error||"Authentication failed"));return}const U=D==null?void 0:D.idToken,y=D==null?void 0:D.accessToken,b=y??U,T=(D==null?void 0:D.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!y,hasIdToken:!!U,hasEmail:!!T}),!b){d.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const C={token:b,email:T},$=B=>{Be.verifyIdTokenNonce(B,l).then(()=>r(C)).catch(M=>{d.error("[CROSSx] nonce 검증 실패:",M),t(M instanceof Error?M:new Error("nonce verification failed"))})};y?y.split(".").length===3?$(y):U?$(U):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(C)):U?$(U):t(new Error("Token not found in response"))};this.abortPending=G=>{Q(),t(new Error(G))},window.addEventListener("message",Y)})}}const at="crossx_wallet_data",Qe="crossx_mock_pin_hash";class La{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(at)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(at);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(at,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Qe,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(at);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()+3e5).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(Qe);return r&&r!==e?!1:(r||await this.storage.set(Qe,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(Qe);if(n&&t&&n!==t)throw new f(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Qe,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(at,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Qe,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("")}}const Ba=["password","newPassword","recoveryPin"];class Me{constructor(e,r,t,n,i,o){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,this.pinEncryptor=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Ar))return e;const r=!e||this.tokenStore.isExpiringSoon(Ar);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 sealPinFields(e){if(!this.pinEncryptor||!e||typeof e!="object")return e;let r=null;for(const t of Ba){const n=e[t];if(typeof n!="string"||n==="")continue;const i=await this.pinEncryptor.seal(n);i!==n&&(r||(r={...e}),r[t]=i)}return r??e}async request(e,r,t,n=!1,i=!1){var u,p,_,x;const o=await this.ensureValidToken(),a=`${this.baseUrl}${r}`,c={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId},l=await this.sealPinFields(t);try{const g=(await this.transport.request({url:a,method:e,headers:c,body:l??void 0})).data;if(g&&typeof g.code=="number"){if(g.code<0||g.code>=400){const m=g.message||g.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:g.code,message:m,url:a,method:e});const E=Me.mapGatewayError(g.code,g.data);if(E===h.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!i))return d.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,r,t,n,!0);if(E===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0,i);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(E===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(u=this._onUnauthorized)==null||u.call(this),new f(h.USER_NOT_FOUND,Me.getGatewayErrorMessage(g.code,m));const I=E===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:E,N=I===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Me.getGatewayErrorMessage(g.code,m),L=g.data;let W;throw E===h.PIN_LOCKED?W=Me.extractLockDetails(L):E===h.ADDRESS_LIMIT_EXCEEDED?W={limit:lt,raw:L}:W=L??void 0,new f(I,N,W)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:g.code,url:a,method:e}),g.data??g}return g}catch(w){if(w instanceof f)throw w;const g=((p=w.response)==null?void 0:p.status)??w.status;if((g===401||g===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${g} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0,i);throw new f(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((_=w.response)!=null&&_.data){const m=w.response.data,E=m.message||m.data||"API 요청에 실패했습니다",I=m.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:I,message:E,url:a,method:e,status:(x=w.response)==null?void 0:x.status}),new f(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${I}): ${E}`)}throw w}}async checkWallet(){var r,t;d.log("[CROSSx] GET /mnemonic/check"),(t=(r=this.pinEncryptor)==null?void 0:r.prewarm)==null||t.call(r);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,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");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 Me.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-10045:return h.PIN_ENCRYPTION_INVALID;case-10046:return h.PIN_POLICY_VIOLATION;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 ${lt} accounts allowed.`;case-10045:return"Could not securely send your PIN. Please try again.";case-10046:return r||"This PIN does not meet the security policy. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class Ma{constructor(e,r,t,n=()=>{},i=()=>{},o=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,this.getAppName=i,this.onBridgeUnauthorized=o,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(a,c)=>e.prepare(a,c)),e.migrateWallet&&(this.migrateWallet=(a,c)=>e.migrateWallet(a,c)),e.verifyPin&&(this.verifyPin=a=>e.verifyPin(a)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(a,c)=>e.verifyRecoveryPin(a,c))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async innerOwnsAddress(e,r){if(!r)return!0;try{return(await this.inner.getAddresses(e)).some(n=>n.address.toLowerCase()===r.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,r,t,n){return!kr(e)||!await this.innerOwnsAddress(r,t)?!1:(this.onBridgeUnauthorized(`native 가 ${n} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();try{const c=await a.signMessage({chainId:r,message:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,o,"signMessage"))throw He(c,h.SIGNATURE_FAILED)}}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();try{const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,o,"signTypedData"))throw He(c,h.SIGNATURE_FAILED)}}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();try{const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}catch(a){if(!await this.recoverFromUnauthorized(a,e,t.from,"signTransaction"))throw He(a,h.SIGNATURE_FAILED)}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,dappName:this.getAppName()})).txHash}}catch(o){if(!await this.recoverFromUnauthorized(o,e,t.from,"sendTransaction"))throw He(o,h.TRANSACTION_FAILED)}}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 ct{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=ct.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?Tn:Rn;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(ct.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=ct.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new f(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(ut).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 rn="__crossx-confirm-style",re="__crossx-confirm-overlay",$a={light:{bg:"#FFFFFF",border:"rgba(0,0,0,0.07)",borderMedium:"rgba(0,0,0,0.18)",titleColor:"#000000",contentHigh:"rgba(0,0,0,0.85)",subtitleColor:"rgba(0,0,0,0.65)",labelColor:"rgba(0,0,0,0.65)",valueColor:"#000000",pillBg:"#F5F7FA",pillFromColor:"rgba(0,0,0,0.65)",pillAmtColor:"#000000",divider:"rgba(0,0,0,0.07)",closeColor:"rgba(0,0,0,0.40)",closeHoverBg:"#F5F7FA",copyColor:"rgba(0,0,0,0.65)",inputBg:"#F5F7FA",inputBorder:"rgba(0,0,0,0.07)",hintColor:"rgba(0,0,0,0.45)",surfaceSubtle:"#F5F7FA",surfaceHigh:"#EDF1F2",primary:"#FF823D",primaryGlow:"rgba(255,130,61,0.20)",primaryGradient:"linear-gradient(191.6deg, #FF2589 16%, #FF823D 84%)",secondary:"#D20609",errorColor:"#D20609",noticeBg:"#FFF6F6",noticeBorder:"#DA0B2E",noticeTitleColor:"#D20609",onPrimary:"#000000"},dark:{bg:"#1E232E",border:"rgba(255,255,255,0.07)",borderMedium:"rgba(255,255,255,0.18)",titleColor:"#FFFFFF",contentHigh:"rgba(255,255,255,0.85)",subtitleColor:"rgba(255,255,255,0.65)",labelColor:"rgba(255,255,255,0.65)",valueColor:"#FFFFFF",pillBg:"#252B39",pillFromColor:"rgba(255,255,255,0.65)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.07)",closeColor:"rgba(255,255,255,0.40)",closeHoverBg:"#252B39",copyColor:"rgba(255,255,255,0.65)",inputBg:"#252B39",inputBorder:"rgba(255,255,255,0.07)",hintColor:"rgba(255,255,255,0.45)",surfaceSubtle:"#252B39",surfaceHigh:"#363B4C",primary:"#FF823D",primaryGlow:"rgba(255,130,61,0.20)",primaryGradient:"linear-gradient(191.6deg, #FF2589 16%, #FF823D 84%)",secondary:"#FF0F47",errorColor:"#FF0F47",noticeBg:"#39151E",noticeBorder:"#CD0C40",noticeTitleColor:"#FF0F47",onPrimary:"#000000"}};function sn(s,e){const r=$a[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,contentHigh: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 Fa=`
6
+ For security, you must continue with the same account.`,update_required_title:"Update required",update_required_message:"This service is using a wallet version that is no longer supported, so you cannot sign in or send transactions right now. Please try again after the service is updated.",update_required_confirm_button:"OK",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"},ci={ko:ai,en:Hr};function be(s="en",e){return ci[s]??Hr}function li(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Gr="crossx_access_token",Kr="crossx_refresh_token",Vr="crossx_user_info",Bt=class Bt{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 d=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${d}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${d}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${d}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${d}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new _(h.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,legacyOauthServiceUrl:a}=this.config,c=li(this.getLocale()),l=g=>{const w=`${g}${i}`,m=w.includes("?")?"&":"?";return`${w}${m}locale=${c}`},d=l(o),p=a?l(a):void 0;u.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),u.log(`[CROSSx] Auth URL: ${d}`);const f=await this.oauth.openAuth({authUrl:d,...p?{legacyAuthUrl:p}:{},expectedOrigin:new URL(o).origin});r=f.token,t=f.email,u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&u.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){if(u.error("[CROSSx] SignIn 에러 (OAuth 단계):",n),n instanceof _)throw n;const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new _(h.OAUTH_POPUP_BLOCKED,i):new _(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return u.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return u.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 d=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=d.firebase)==null?void 0:t.sign_in_provider);const p=((n=d.firebase)==null?void 0:n.identities)??{};c=d.email??((i=p.email)==null?void 0:i[0]),u.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{u.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const d=await this.crypto.verifyJWT(a);if(!d.valid)throw new _(h.AUTH_FAILED,"Access token 검증 실패");const p=d.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),u.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),u.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new _(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 u.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return u.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:d}=this.config,{accessToken:p,refreshToken:f}=await this.exchangeFirebaseToken(e,d);let g,w,m;try{const S=this.crypto.decodeJWT(e);u.log("[CROSSx] Firebase JWT 필드:",Object.keys(S).join(", ")),w=(i=S.firebase)==null?void 0:i.sign_in_provider;const I=((o=S.firebase)==null?void 0:o.identities)??{};m=S.email??((a=I.email)==null?void 0:a[0]),w==="google.com"?g=(c=I["google.com"])==null?void 0:c[0]:w==="apple.com"&&(g=(l=I["apple.com"])==null?void 0:l[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",w,"hasProviderSub:",!!g,"email:",m??"(없음)")}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const S=this.crypto.decodeJWT(p);u.log("[CROSSx] access_token 디코딩 — sub:",S.sub,"exp:",S.exp,"필드:",Object.keys(S).join(", "));const I=await this.crypto.verifyJWT(p);if(n=I.signatureVerified??!1,!I.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const U=I.payload,C=U.email??m??r;u.log("[CROSSx] email 소스 — CROSSx JWT:",U.email??"(없음)","/ Firebase JWT:",m??"(없음)","/ OAuth 콜백:",r??"(없음)","→",C??"(없음)"),t={id:U.sub,email:C,signInProvider:w,providerSub:g},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),f&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,f):f&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const S=this.crypto.decodeJWT(e);t={id:S.sub,email:S.email??r,signInProvider:w,providerSub:g},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}u.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const x=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,x),await this.clearStoredRNBridgeSession(),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(d){return u.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",d),{success:!1,error:d instanceof Error?d.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;u.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){u.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new _(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}u.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 _(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return u.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`;u.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"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.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 u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.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(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return u.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return u.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;u.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof _&&e.code===h.SESSION_EXPIRED;return u.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 d=this.tokenStore.get()??"";d&&(i.access_token=d),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"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const d=Bt.REFRESH_RELOGIN_CODES.has(c.code);throw new _(d?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new _(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const d=this.extractRefreshToken(a);d&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,d)}return u.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){u.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),u.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof _&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(u.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):(u.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof _&&e.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):u.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 u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return u.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 u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;u.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),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return u.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(Vr);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(Gr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Kr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Vr),await this.storage.remove(Gr),await this.storage.remove(Kr),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",i),i==="migration_required")u.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,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof _&&i.code===h.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof _&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED||i.code===h.SDK_VERSION_UNSUPPORTED))throw u.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};Bt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Ft=Bt;class di{constructor(e,r,t,n=[]){this.config=e,this.storage=r,this.tokenStore=t,this.preservedKeys=n;const i=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${i}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${i}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${i}_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);const e=[];for(const r of this.preservedKeys){const t=await this.storage.get(r).catch(()=>null);t!=null&&e.push([r,t])}await this.storage.clear();for(const[r,t]of e)await this.storage.set(r,t).catch(()=>{})}}class ui{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new _(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Wt{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}}const hi="/authorize/result",pi="one-oauth:authorization_response",qr="one-oauth:authorization_error",_i="one-oauth:authorization_ack",fi="openid profile offline_access";function Ht(s){let e="";for(const r of s)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function zr(s=32){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ht(e)}async function Jr(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Ht(new Uint8Array(e))}function ft(s=16){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ht(e)}const gi=300*1e3,xi=600*1e3,Gt="crossx.oneid.pending",wi=1e3,mi=10;function jr(s){switch(s){case"access_denied":return h.USER_REJECTED;case"required_items_not_agreed":return h.ONEID_TERMS_NOT_AGREED;case"account_not_found":return h.ONEID_ACCOUNT_NOT_FOUND;case"service_not_linked":return h.ONEID_SERVICE_NOT_LINKED;default:return h.ONEID_AUTHORIZATION_FAILED}}function yi(s){switch(s){case"session_evicted":return h.ONEID_SESSION_EVICTED;case"session_revoked":return h.ONEID_SESSION_REVOKED;case"session_expired":return h.ONEID_SESSION_EXPIRED;default:return h.ONEID_SESSION_INVALID}}function Kt(s){if(!(typeof s!="string"||!s.startsWith("/"))&&!(s.startsWith("//")||s.startsWith("/\\")))return s}function Ge(s){let e;try{e=new URL(s)}catch{throw new _(h.INVALID_CONFIG,"ONE ID issuer가 올바른 URL이 아닙니다")}return e.toString().replace(/\/+$/,"")}function Yr(s){const e=s.split(".")[1];if(!e)return null;try{const r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=new TextDecoder().decode(Uint8Array.from(atob(t),o=>o.charCodeAt(0))),i=JSON.parse(n);return typeof i=="object"&&i!==null?i:null}catch{return null}}function bi(s){if(typeof s!="object"||s===null)return!1;const e=s.type;return e===pi||e===qr}function Xr(s,e){if(typeof s.access_token!="string"||s.access_token==="")throw new _(h.ONEID_AUTHORIZATION_FAILED,"토큰 응답에 access_token이 없습니다");const r=typeof s.expires_in=="number"?s.expires_in:0;return{accessToken:s.access_token,tokenType:typeof s.token_type=="string"?s.token_type:"Bearer",expiresAt:e+r*1e3,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:void 0,idToken:typeof s.id_token=="string"?s.id_token:void 0,scope:typeof s.scope=="string"?s.scope:void 0}}class Si{constructor(){this.reason=null,this.onAbort=null}abort(e){var r;this.reason??(this.reason=e),(r=this.onAbort)==null||r.call(this,e)}throwIfAborted(){if(this.reason!==null)throw new _(h.USER_REJECTED,this.reason)}}class vi{constructor(e={}){this.abortPending=null,this.popupSeq=0,this.options=e}get fetchImpl(){return this.options.fetch??((e,r)=>fetch(e,r))}now(){var e,r;return((r=(e=this.options).now)==null?void 0:r.call(e))??Date.now()}get pendingStorage(){return this.options.pendingStorage??window.sessionStorage}cancelPending(e="ONE ID 로그인 대기를 중단했습니다"){var r;(r=this.abortPending)==null||r.call(this,e)}async authorize(e){let r=null;if(e.mode!=="redirect"&&(r=this.openBlankPopup(e.width,e.height),!r&&e.mode==="popup"))throw new _(h.OAUTH_POPUP_BLOCKED,"팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요.");try{const t=Ge(e.issuer);if(!e.clientId)throw new _(h.INVALID_CONFIG,"ONE ID clientId가 비어 있습니다");this.cancelPending("새 ONE ID 로그인 요청으로 이전 대기를 중단했습니다");const n=new Si,i=o=>n.abort(o);this.abortPending=i;try{return r?await this.authorizeWithPopup(r,{...e,issuer:t},n):await this.authorizeWithRedirect({...e,issuer:t},n)}finally{this.abortPending===i&&(this.abortPending=null)}}catch(t){try{r==null||r.close()}catch{}throw t}}async completeRedirect(e,r){const t=Ge(e.issuer),n=this.takePending(),i=new URL(r).searchParams;if(!n||n.issuer!==t||n.clientId!==e.clientId)throw new _(h.ONEID_STATE_MISMATCH,"진행 중인 ONE ID 로그인이 없습니다. 다시 로그인해 주세요.");if(this.now()-n.createdAt>xi)throw new _(h.ONEID_TIMEOUT,"ONE ID 로그인 시간이 지났습니다");const o=i.get("state");if(!o||o!==n.state)throw new _(h.ONEID_STATE_MISMATCH,"ONE ID 로그인 결과의 state가 다릅니다");if(i.get("iss")!==t)throw new _(h.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다");const a=i.get("error");if(a){const d=i.get("error_description")??void 0;throw new _(jr(a),d||`ONE ID 인가 오류: ${a}`,{error:a,error_description:d})}const c=i.get("code");if(!c)throw new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다");return{tokens:await this.exchangeCode({...e,issuer:t},c,n.codeVerifier,n.redirectUri,n.nonce),returnTo:Kt(n.returnTo)}}async refresh(e,r){const t=Ge(e.issuer),n=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:r});let i;try{i=await this.fetchImpl(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})}catch(c){throw new _(h.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",c)}const o=await Vt(i);if(!i.ok){if(i.status===400&&o.error==="invalid_grant"){const c=typeof o.error_reason=="string"?o.error_reason:void 0;throw new _(yi(c),"ONE ID 세션이 끝났습니다. 다시 로그인해 주세요.",{error:"invalid_grant",error_reason:c})}throw i.status>=400&&i.status<500&&i.status!==408&&i.status!==429?new _(h.ONEID_SESSION_INVALID,"ONE ID 세션을 갱신할 수 없습니다. 다시 로그인해 주세요.",{status:i.status,error:o.error}):new _(h.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",{status:i.status,error:o.error})}const a=Xr(o,this.now());return{...a,refreshToken:a.refreshToken??r}}async logout(e,r){const t=Ge(e.issuer);let n;try{n=await this.fetchImpl(`${t}/logout`,{method:"POST",headers:{Authorization:`Bearer ${r}`}})}catch(i){throw new _(h.NETWORK_ERROR,"ONE ID 로그아웃 요청을 보내지 못했습니다",i)}if(!n.ok&&n.status!==401)throw new _(h.NETWORK_ERROR,"ONE ID 로그아웃 요청이 실패했습니다",{status:n.status})}openBlankPopup(e=500,r=700){const t=Math.max(e,500),n=Math.max(r,700),i=window.screenX+(window.outerWidth-t)/2,o=window.screenY+(window.outerHeight-n)/2;try{return this.popupSeq+=1,window.open("about:blank",`ONEidLogin${this.popupSeq}`,`width=${t},height=${n},left=${i},top=${o}`)}catch{return null}}async pushAuthorizationRequest(e,r,t,n,i){const o=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:r,scope:e.scope??fi,state:t,nonce:n,code_challenge:i,code_challenge_method:"S256"});let a;try{a=await this.fetchImpl(`${e.issuer}/par`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})}catch(l){throw new _(h.NETWORK_ERROR,"ONE ID 로그인 요청을 보내지 못했습니다",l)}const c=await Vt(a);if(!a.ok||typeof c.request_uri!="string")throw new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 요청이 거부되었습니다",{status:a.status,error:c.error});return c.request_uri}authorizeUrl(e,r){const t=new URL(`${e.issuer}/authorize`);return t.searchParams.set("client_id",e.clientId),t.searchParams.set("request_uri",r),t.toString()}async exchangeCode(e,r,t,n,i){const o=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:r,redirect_uri:n,code_verifier:t});let a;try{a=await this.fetchImpl(`${e.issuer}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})}catch(d){throw new _(h.NETWORK_ERROR,"ONE ID 토큰을 받지 못했습니다",d)}const c=await Vt(a);if(!a.ok)throw new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 토큰 교환이 거부되었습니다",{status:a.status,error:c.error});const l=Xr(c,this.now());if(l.idToken){const d=Yr(l.idToken);if(!d||d.iss!==e.issuer||d.nonce!==i)throw new _(h.ONEID_ISSUER_MISMATCH,"ONE ID id_token의 발급자나 nonce가 요청과 다릅니다")}return l}async authorizeWithPopup(e,r,t){const n=new URL(r.issuer).origin,i=`${r.issuer}${hi}`,o=ft(),a=ft(),c=zr(),l=await Jr(c),d=await this.pushAuthorizationRequest(r,i,o,a,l);t.throwIfAborted(),u.log("[CROSSx] ONE ID 로그인 팝업 이동",{issuer:r.issuer,clientId:r.clientId}),e.location.href=this.authorizeUrl(r,d);const p=await new Promise((g,w)=>{let m=0,x=!0;const S=()=>{t.onAbort=null,clearTimeout(U),clearInterval(C),window.removeEventListener("message",L)},I=H=>{S(),w(H)},U=setTimeout(()=>{I(new _(h.ONEID_TIMEOUT,"ONE ID 로그인 응답 시간이 지났습니다"))},gi),C=setInterval(()=>{if(!x)return;m++;let H;try{H=e.closed}catch{x=!1;return}if(!H)return;const G=typeof document<"u"&&document.hasFocus();if(m<=mi&&!G){u.warn("[CROSSx] ONE ID 팝업 closed 오탐 가능성(COOP) — 결과 대기 유지"),x=!1;return}I(new _(h.USER_REJECTED,"ONE ID 로그인이 취소되었습니다"))},wi),L=H=>{if(H.origin!==n||H.source!==e||!bi(H.data))return;const G=H.data;if(G.state!==o){u.warn("[CROSSx] ONE ID 결과 state가 현재 요청과 달라 무시합니다");return}try{e.postMessage({type:_i,state:o},n)}catch{}if(G.iss!==r.issuer){I(new _(h.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다"));return}if(G.type===qr||G.error){const q=G.error??"unknown_error";u.warn("[CROSSx] ONE ID 인가 오류:",q),I(new _(jr(q),G.error_description||`ONE ID 인가 오류: ${q}`,{error:q,error_description:G.error_description}));return}if(!G.code){I(new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다"));return}S(),g(G.code)};t.onAbort=H=>{I(new _(h.USER_REJECTED,H))},window.addEventListener("message",L)}),f=await this.exchangeCode(r,p,c,i,a);return u.log("[CROSSx] ONE ID 로그인 완료 (팝업)"),{status:"completed",tokens:f,returnTo:Kt(r.returnTo)}}async authorizeWithRedirect(e,r){const t=e.redirectUri??`${window.location.origin}/auth/callback`;if(new URL(t).origin!==window.location.origin)throw new _(h.INVALID_CONFIG,"ONE ID redirectUri는 지금 페이지와 같은 origin이어야 합니다");const n=ft(),i=ft(),o=zr(),a=await Jr(o),c=await this.pushAuthorizationRequest(e,t,n,i,a);r.throwIfAborted();const l={issuer:e.issuer,clientId:e.clientId,state:n,nonce:i,codeVerifier:o,redirectUri:t,returnTo:Kt(e.returnTo),createdAt:this.now()};this.pendingStorage.setItem(Gt,JSON.stringify(l)),u.log("[CROSSx] ONE ID 로그인 같은 창 이동",{issuer:e.issuer,clientId:e.clientId});const d=this.authorizeUrl(e,c);return(this.options.navigate??(p=>window.location.assign(p)))(d),{status:"redirecting"}}takePending(){const e=this.pendingStorage.getItem(Gt);if(this.pendingStorage.removeItem(Gt),!e)return null;try{const r=JSON.parse(e);return typeof(r==null?void 0:r.state)=="string"&&typeof r.codeVerifier=="string"?r:null}catch{return null}}}async function Vt(s){try{const e=await s.json();return typeof e=="object"&&e!==null?e:{}}catch{return{}}}const gt="crossx.oneid.session",Zr=60*1e3,Qr=new Set([h.ONEID_SESSION_EVICTED,h.ONEID_SESSION_REVOKED,h.ONEID_SESSION_EXPIRED,h.ONEID_SESSION_INVALID]);class Ei{constructor(e,r,t,n=()=>Date.now()){this.port=e,this.config=r,this.storage=t,this.now=n,this.refreshing=null,this.generation=0}save(e){this.generation+=1;const r={issuer:Ge(this.config.issuer),clientId:this.config.clientId,tokens:e};return this.storage.setItem(gt,JSON.stringify(r)),es(r)}async get(){const e=await this.ensureFresh();return e?es(e):null}async getAccessToken(){const e=await this.ensureFresh();if(!e)throw new _(h.AUTH_NOT_AUTHENTICATED,"ONE ID로 로그인하지 않았습니다");return e.tokens.accessToken}async signOut(){const e=this.read();if(this.clear(),!e)return;let r=e.tokens.accessToken;if(e.tokens.refreshToken&&e.tokens.expiresAt-Zr<=this.now())try{r=(await this.port.refresh(this.config,e.tokens.refreshToken)).accessToken}catch(t){if(t instanceof _&&Qr.has(t.code))return}await this.port.logout(this.config,r)}clear(){this.generation+=1,this.storage.removeItem(gt)}read(){var r;const e=this.storage.getItem(gt);if(!e)return null;try{const t=JSON.parse(e);return typeof((r=t==null?void 0:t.tokens)==null?void 0:r.accessToken)=="string"&&typeof t.tokens.expiresAt=="number"&&t.issuer===Ge(this.config.issuer)&&t.clientId===this.config.clientId?t:(this.clear(),null)}catch{return this.clear(),null}}async ensureFresh(){const e=this.read();if(!e)return null;if(e.tokens.expiresAt-Zr>this.now())return e;if(!e.tokens.refreshToken){if(e.tokens.expiresAt>this.now())return e;throw this.clear(),new _(h.ONEID_SESSION_EXPIRED,"ONE ID 로그인이 만료되었습니다. 다시 로그인해 주세요.")}return this.refreshing??(this.refreshing=this.refresh(e).finally(()=>{this.refreshing=null})),this.refreshing}async refresh(e){const r=this.generation;try{const t=await this.port.refresh(this.config,e.tokens.refreshToken),n={...e,tokens:t};if(r!==this.generation)throw new _(h.AUTH_NOT_AUTHENTICATED,"ONE ID 세션이 바뀌었습니다");return this.storage.setItem(gt,JSON.stringify(n)),n}catch(t){if(r!==this.generation)throw t;if(t instanceof _&&Qr.has(t.code))throw this.clear(),t;if(e.tokens.expiresAt>this.now())return e;throw t}}}function es(s){const e=s.tokens.idToken?Yr(s.tokens.idToken):null;return{subject:typeof(e==null?void 0:e.sub)=="string"?e.sub:"",clientId:s.clientId,issuer:s.issuer,scope:s.tokens.scope,expiresAt:s.tokens.expiresAt}}function Ii(s){return s==="local"?window.localStorage:window.sessionStorage}const Ai=3,Ti=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function Ri(s){return s.code===Ai||/execution reverted/i.test(s.message??"")}class Ni{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){const{code:c,message:l}=a.error,d={method:e,chainId:t,code:c,message:l,data:a.error.data},p=Ri(a.error);throw p&&typeof d.data=="string"&&Ti.test(d.data)&&(d.revertData=d.data,d.selector=d.data.slice(0,10).toLowerCase()),new _(p?h.EXECUTION_REVERTED:h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${l} (코드: ${c})`,d)}return a==null?void 0:a.result}}class Ci{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 Oi(){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 u.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return u.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)||u.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=fe.getBridge(),!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw u.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new _(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,u.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=Oi(),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 _(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,a=n.provider==="google"||n.provider==="apple"?n.provider: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,walletProvider:a}}catch(n){throw u.error("[RNBridge] Handshake failed",n),new _(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new _(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 _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof _)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new _(h.USER_REJECTED,"Firebase ID token request rejected by user",e):(u.error("[RNBridge] Firebase token request failed",e),new _(h.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new _(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 _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof _?e:(u.error("[RNBridge] Fresh Firebase token request failed",e),new _(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new _(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 _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof _?r:(u.warn("[RNBridge] Session restore Firebase token request failed",r),new _(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 _(h.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var xt={environment:"production"};const Ke={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:""},staging:{oauthServiceUrl:"https://stg-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://stg-oauth2.onechain.nexus"},development:{oauthServiceUrl:"https://dev-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://dev-oauth2.onechain.nexus"}};function ki(s){const e=s.environment,r=e&&e in Ke?Ke[e]:null;if(!r)return null;const t=s.overrides;if(!t)return r;const n={...r};for(const[i,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(n[i]=o);return n}function wt(){try{if(typeof xt<"u"){const s=typeof xt=="string"?JSON.parse(xt):xt,e=ki(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Ke)return Ke[s]}catch{}return Ke.production}function ts(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Pi(s,e=$t){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Dr),n=r/t,o=(r%t).toString().padStart(Dr,"0"),a=ts(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function mt(s,e,r,t=$t){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=ts(c.slice(0,t)),d=l?`${o}.${l}`:`${o}`;return e?`${d} ${e}`:d}catch{return}}function Di(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Pr)throw new _(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Pr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Li(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Bi(s,e){const r=Mi(e);if(s==="0"){if(r!==void 0&&r!==0)throw new _(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 _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Mi(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 Ve{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new _(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){var c,l;if((l=(c=this.deps).isRNBridgeMode)!=null&&l.call(c))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((d,p)=>{i=d,o=p});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const p=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!p)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(p),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const d=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async p=>{this.deps.pinStore.set(p);try{return await this.deps.walletProvider.verifyPin(p)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(f){if(this.deps.pinStore.clear(),f instanceof _){if(f.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(f.code===h.PIN_INVALID)return{ok:!1,error:f.message};if(f.code===h.PIN_LOCKED)return Ve.buildPinLockedResult(f,a)}throw f}}});if(!d)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(d),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(d){if(d instanceof _&&(d.code===h.AUTH_NOT_AUTHENTICATED||d.code===h.AUTH_TOKEN_EXPIRED||d.code===h.SESSION_EXPIRED)&&d.code!==h.SESSION_EXPIRED){const p=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:f?this.deps.maskEmail(f,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(d),d}throw o(d),d}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof _){if(t=Ve.parsePinError(n,r),!t)throw n}else throw n}for(;;){u.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 _&&(t=Ve.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=Ve.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class $i{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 _(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 Ui(s){return s==="google"||s==="apple"}class Fi{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=Ui(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)){u.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(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{u.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return u.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=be(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 _&&r.code===h.WITHDRAW_FAILED){if(u.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 _&&r.code===h.WALLET_NOT_FOUND){if(u.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 _)||r.code!==h.SESSION_EXPIRED)throw r;if(u.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 _(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new _(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Wi{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return u.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(u.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(f=>f.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?u.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const d=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,d?{walletName:t}:void 0);return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Hi{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const d=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(d===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.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,d,e));if(!p){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=d;break}if(p.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=d;break}const f=p.pinStatus;if(o=f.maxAttempts,i=o-f.remainingAttempts,f.remainingAttempts===0&&f.lockExpiresAt){const g=f.lockExpiresAt*1e3,w=Math.max(1,Math.round((g-Date.now())/1e3)),m=w<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${w}초, 메시지: ${m}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,m),i=0,n="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof _))throw p;if(p.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const f=be(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:f.session_alert_title,message:f.alert_session_expired,email:g?this.deps.maskEmail(g,f.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const f=p.details;if(o=(f==null?void 0:f.maxAttempts)??5,(f==null?void 0:f.permanent)===!0)return u.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=((f==null?void 0:f.lockExpiresAt)??0)*1e3,w=Math.max(1,Math.round((g-Date.now())/1e3)),m=w<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${w}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,m),i=0,n="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const d=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",d.address),d}catch(d){if(d instanceof _&&d.code===h.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(d instanceof _&&d.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:f?this.deps.maskEmail(f,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const m=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",m.address),m}catch(m){throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",m),m}}throw this.deps.clearAuthState(),d}throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",d),d}}}class Gi{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=g=>!(g!=null&&g.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&&u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[d,p,f]=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(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const g=f;if(g){const w=kr;c.maxFeePerGas=`0x${(BigInt(g)+BigInt(w)).toString(16)}`,c.maxPriorityFeePerGas=w,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",g,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Vn,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=kr,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ki{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 u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Vi(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class qi{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,r){var n,i,o,a,c;const t={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:Vi((a=e.user)==null?void 0:a.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(t),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...r?{source:r}:{}})}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.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class zi{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new _(h.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 Ji{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new _(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new _(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class ji{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;u.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 _(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),u.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof _&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;u.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 _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function rs(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Yi{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new _(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new _(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 _(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new _(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=rs(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{u.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"),u.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof _?c:new _(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(rs(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{u.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 _(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),u.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof _?i:new _(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 _&&c.message.includes("404")&&a<i-1){u.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(d=>setTimeout(d,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 _(n.code,n.message)}}function qt(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 Ci{constructor(e,r,t,n,i,o,a,c,l,d,p,f,g){var w,m;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.pinEncryptor=f,this.oneIdAuth=g,this._warnedUnknownNativeCurrency=new Set,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._sdkDeprecationNotified=!1,this._sdkUnsupportedNotified=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&Wr(e.logger),this.confirmation=l,this.pinStore=p??new Wt,this.stateManager=new qi({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:S,walletName:I})=>{const U={address:x,index:S};I!==void 0&&(U.walletName=I),this.emit("addressChanged",U)},emitAuthChanged:({isAuthenticated:x,address:S,userId:I,source:U})=>{this.emit("authChanged",{isAuthenticated:x,address:S,userId:I,...U?{source:U}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Re.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ve({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:qt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new $i({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Wi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,S,I)=>this.setActiveWallet(x,S,I)}),this.migrationOrchestrator=new Hi({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,S)=>this.migrateWalletUseCase.execute(x,S),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:qt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new Gi({getActiveAddress:()=>this.address,estimateGas:(x,S)=>this.estimateGas(x,S),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,S,I)=>this.jsonRpc.call(x,S,I)}),this.signatureVerifier=new Ki(this.crypto),this.addressResolverService=new zi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Ji({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new ji({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,S)=>this.setActiveWallet(x,S),showWalletCreated:()=>{var x,S;return((S=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:S.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Yi({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Fi({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:qt}),this.chainRegistry=d,this.jsonRpc=new Ni(d,i),this.signInUseCase=new Ft(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new di(this.internalConfig,t,c,this._config.persistWalletPreference!==!1?[Re.WALLET_PREF_KEY]:[]),this.migrateWalletUseCase=new ui(t,a),(w=a.setOnUnauthorized)==null||w.call(a,()=>this.forceLogout()),(m=a.setTokenRefresher)==null||m.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}handleSdkVersionDeprecation(e){if(this._sdkDeprecationNotified)return;this._sdkDeprecationNotified=!0;const r=ut;console.warn(`[CROSSx] ${r} is deprecated`+(e.sunset?` and will stop working on ${e.sunset}`:"")+". Update @nexus-cross/crossx-sdk-core."+(e.infoUrl?` See ${e.infoUrl}`:"")),this.emit("versionDeprecated",{version:r,sunset:e.sunset,infoUrl:e.infoUrl})}handleSdkVersionUnsupported(e){this._sdkUnsupportedNotified||(this._sdkUnsupportedNotified=!0,console.error(`[CROSSx] ${ut} is no longer supported by the wallet gateway. Update @nexus-cross/crossx-sdk-core.`+(e.message?` (${e.message})`:"")),this.confirmation.showUpdateRequired().catch(r=>{u.warn("[CROSSx] 업데이트 필요 모달 표시 실패:",r)}))}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,u.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(r){u.warn("[CROSSx] 저장된 bridge 세션 마커 제거 실패",r)}}}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;u.log("[CROSSx SDK] v2.6.0-beta.1 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=wt();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=n.legacyOauthServiceUrl,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()&&u.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()),d=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,d?{walletName:d}:void 0);else try{await this.loadWalletAfterAuth(o,a,d)}catch(p){if(p instanceof _&&p.code===h.PIN_CANCELLED)u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(p instanceof _&&(p.code===h.SESSION_EXPIRED||p.code===h.AUTH_NOT_AUTHENTICATED||p.code===h.USER_NOT_FOUND))u.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",p.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw p}}return this.initialized=!0,u.info("[CROSSx SDK] v2.6.0-beta.1 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new _(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!fe.isAvailable())return null;try{u.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),u.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.6.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new fe({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.6.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),u.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,u.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 u.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return u.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),u.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const r=this._rnBridgeService.getContext(),t=Date.now();u.info("[CROSSx] Bridge 세션 만료 감지 — 재핸드셰이크 시도",{elapsedSinceActivatedMs:r?t-r.activatedAt:"(context 없음)",idleMs:r?t-r.lastActivityAt:"(context 없음)",absoluteTtlMs:(r==null?void 0:r.absoluteTtlMs)??"(context 없음)",idleTtlMs:(r==null?void 0:r.idleTtlMs)??"(context 없음)",absoluteExpired:r?t-r.activatedAt>r.absoluteTtlMs:"(context 없음)",idleExpired:r?t-r.lastActivityAt>r.idleTtlMs:"(context 없음)"});try{const n=Date.now(),i=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=i.walletAddress,this._rnBridgeWalletName=i.walletName,this._rnBridgeWalletProvider=i.walletProvider,u.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-n,walletAddress:i.walletAddress??"(없음)",walletName:i.walletName??"(없음)",absoluteTtlMs:i.absoluteTtlMs,idleTtlMs:i.idleTtlMs})}catch(n){return u.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",n),this._rnBridgeService=null,null}}try{const r=await this._rnBridgeService.requestFirebaseIdToken();u.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),u.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof _&&r.code===h.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),u.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):r instanceof _&&r.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(u.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())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;u.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,u.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(this._isAuthenticatedViaRNBridge=!1,u.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return this._isAuthenticatedViaRNBridge=!1,u.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new _(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw u.error("[CROSSx] Bridge session restore token request failed:",e),new _(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 _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&u.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let t=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:Qn(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new _(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(t);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof _?n:new _(h.AUTH_FAILED,"로그인에 실패했습니다",n)}}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 _&&i.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){var t,n;if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r,"external"),(n=(t=this.oauth).cancelPending)==null||n.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof _?i:new _(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c);return{...r,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:i}}catch(i){throw i instanceof _&&i.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>u.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),i}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new _(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 _?t:new _(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}signInWithOneId(e){var o,a;let r;try{r=this.oneIdContext()}catch(c){return Promise.reject(c)}const{port:t,config:n,sessions:i}=r;return t.authorize({...n,mode:(e==null?void 0:e.mode)??((o=this._config.oneId)==null?void 0:o.mode)??"auto",redirectUri:(a=this._config.oneId)==null?void 0:a.redirectUri,returnTo:e==null?void 0:e.returnTo}).then(c=>c.status==="redirecting"?c:{status:"signed-in",session:i.save(c.tokens),returnTo:c.returnTo})}async completeOneIdSignIn(e=window.location.href){const{port:r,config:t,sessions:n}=this.oneIdContext(),{tokens:i,returnTo:o}=await r.completeRedirect(t,e);return{session:n.save(i),returnTo:o}}async getOneIdSession(){return this.oneIdContext().sessions.get()}async getOneIdAccessToken(){return this.oneIdContext().sessions.getAccessToken()}async signOutOneId(){await this.oneIdContext().sessions.signOut()}oneIdContext(){this.ensureInitialized();const e=this._config.oneId;if(!this.oneIdAuth||!(e!=null&&e.clientId))throw new _(h.NOT_IMPLEMENTED,"이 환경에서는 ONE ID 로그인을 사용할 수 없습니다 (SDKConfig.oneId 필요)");const r=e.issuer||wt().oneIdIssuer;if(!r)throw new _(h.NOT_IMPLEMENTED,"ONE ID issuer가 정해지지 않았습니다. SDKConfig.oneId.issuer를 지정하세요");const t={issuer:r,clientId:e.clientId,scope:e.scope};return this._oneIdSessions??(this._oneIdSessions=new Ei(this.oneIdAuth,t,Ii(e.storage))),{port:this.oneIdAuth,config:t,sessions:this._oneIdSessions}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=fe.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),u.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){u.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new _(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 _&&t.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof _&&t.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),u.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof _?r:new _(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(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,r){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let t=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));t.length===0&&this.address&&(t=[{address:this.address,index:0}]);const n=await this.confirmation.showWalletSelector(t,async()=>{await this.pinOrchestrator.ensurePinForSigning();const i=t.length,a={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,i)))).address,index:i};return t.push(a),a},e,r);return n&&this.setActiveWallet(n.address,n.index),n}async selectWalletIfMultiple(e,r){if(e.length<2)return null;const t=this._isAuthenticatedViaRNBridge?this._rnBridgeWalletAddress??this.address??void 0:void 0,n=!t&&this._config.persistWalletPreference!==!1?await this.storage.get(Re.WALLET_PREF_KEY).catch(()=>null):null,i=t?[t,r]:[r,n==null?void 0:n.address];for(const o of i){if(typeof o!="string"||!o)continue;const a=e.find(c=>c.address.toLowerCase()===o.toLowerCase());if(a)return this.setActiveWallet(a.address,a.index),a}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof _?r:new _(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(be(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}resolveNativeCurrency(e){const r=oi(e,this._config.nativeCurrencies);return r||(this._warnedUnknownNativeCurrency.has(e)||(this._warnedUnknownNativeCurrency.add(e),console.warn(`[CROSSx SDK] ${e} 의 native 통화 정보가 없어 심볼을 비우고 decimals 를 18 로 가정합니다. 컨펌 모달 금액이 단위 없이 표시되며, decimals 가 18 이 아니면 금액이 틀립니다. SDKConfig.nativeCurrencies 에 { '${e}': { symbol, decimals } } 를 넘겨 주세요.`)),ii)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const n=fe.getBridge(),i=this._isAuthenticatedViaRNBridge||!this.authenticated;if(n!=null&&n.signMessage&&i)try{const a=await n.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:a.signature,message:r,address:this.address??""}}catch(a){if(!Ur(a))throw He(a,h.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),u.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const o=await this.resolveAddress(t==null?void 0:t.index);try{const a=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:o.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:o.address},execute:c=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,c,o.address)});return this.signatureVerifier.verifySignatureSigner(r,a.signature,o.address),{chainId:e,signature:a.signature,message:r,address:o.address}}catch(a){throw a instanceof _?a:new _(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,a)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Bi(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 Di(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof _?i:new _(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 _(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=this.resolveNativeCurrency(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 Li(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof _)throw o;const a=o instanceof Error?o.message:String(o);throw new _(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 _(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=this.resolveNativeCurrency(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 d=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,d)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,d);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,ut).catch(d=>u.log("[TokenHistory] register failed (non-critical):",d)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof _)throw o;const a=o instanceof Error?o.message:String(o);throw new _(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??Gn,i=Kn,o=t.timeoutMs??Or,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(d=>setTimeout(d,c)),c=Math.min(c*2,i)}throw new _(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var m,x;if(this._isAuthenticatedViaRNBridge){const S=fe.getBridge();if(S!=null&&S.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(S,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((m=this._config.receiptPolling)==null?void 0:m.intervalMs)??Hn,l=i??((x=this._config.receiptPolling)==null?void 0:x.timeoutMs)??Or,d=this.resolveNativeCurrency(e),p=r.from??"";let f,g;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{f=S;const I=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),U=r.value?BigInt(r.value):0n,C=mt(r.value,d.symbol,d.decimals,this._config.displayDecimals),L=mt("0x"+I.toString(16),d.symbol,d.decimals,this._config.displayDecimals),H=mt("0x"+(U+I).toString(16),d.symbol,d.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:S.from,to:S.to??r.to,amount:C,fees:L,total:H,nativeSymbol:d.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(g=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:p,to:r.to,amount:mt(r.value,d.symbol,d.decimals,this._config.displayDecimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},w),g)throw g;return{chainId:e,txHash:a,receipt:f}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){let i;try{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??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs})}catch(o){throw He(o,h.TRANSACTION_FAILED)}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 _(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof _?n:new _(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 _(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){if(n instanceof _&&n.code===h.EXECUTION_REVERTED)throw n;const i=n instanceof Error?n.message:String(n);throw new _(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 _(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 _(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 _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(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:Pi(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new Ut(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){u.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 _)throw n;const i=n instanceof Error?n.message:String(n);throw new _(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)){u.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){u.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){u.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)){u.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){u.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){u.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()||(u.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)}),u.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,r){this.stateManager.applyAuthResult(e,r)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(u.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(),Wr(null)}};Re.WALLET_PREF_KEY="wallet_preference",Re.OFFCHAIN_CHAIN_ID="0";let tt=Re;class Xi{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.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 u.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw u.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw u.error("Storage clear error:",e),e}}}const yt="crossx-sdk",ss=1,he="data",Ne="keys",bt="aes-primary",Zi=12;class ns{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(){return new Promise((e,r)=>{const t=indexedDB.open(this.dbName,ss);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(he)||n.createObjectStore(he),n.objectStoreNames.contains(Ne)||n.createObjectStore(Ne)},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error)})}openLegacyIfExists(){return new Promise((e,r)=>{let t=!1;const n=indexedDB.open(yt,ss);n.onupgradeneeded=()=>{t=!0},n.onsuccess=()=>{const i=n.result;if(t){i.close(),this.deleteDB(yt).then(()=>e(null));return}if(!i.objectStoreNames.contains(Ne)||!i.objectStoreNames.contains(he)){i.close(),e(null);return}e(i)},n.onerror=()=>r(n.error)})}deleteDB(e){return new Promise(r=>{const t=indexedDB.deleteDatabase(e);t.onsuccess=()=>r(),t.onerror=()=>{u.warn("[CROSSx] IndexedDB 삭제 실패:",e,t.error),r()},t.onblocked=()=>{u.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),r()}})}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(Ne,bt);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(Ne,bt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===yt)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const r=e.transaction([Ne,he],"readonly"),t=r.objectStore(Ne).get(bt),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const i=r.objectStore(he).getAll(),o=r.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)}),new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)})]);e.close(),await this.idbPut(Ne,bt,n);for(let l=0;l<c.length;l++)await this.idbPut(he,String(c[l]),a[l]);return await this.deleteDB(yt),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Zi);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(he,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(he,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return u.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(he,e)}catch(r){throw u.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(he)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const zt=crypto,is=s=>s instanceof CryptoKey,St=new TextEncoder,rt=new TextDecoder;function Qi(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const eo=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Ce=s=>{let e=s;e instanceof Uint8Array&&(e=rt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return eo(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class se extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}se.code="ERR_JOSE_GENERIC";class pe extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}pe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Jt extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Jt.code="ERR_JWT_EXPIRED";class os extends se{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}os.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends se{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class to extends se{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}to.code="ERR_JWE_DECRYPTION_FAILED";class ro extends se{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ro.code="ERR_JWE_INVALID";class re extends se{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}re.code="ERR_JWS_INVALID";class xe extends se{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class so extends se{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}so.code="ERR_JWK_INVALID";class jt extends se{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}jt.code="ERR_JWKS_INVALID";class Yt extends se{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Yt.code="ERR_JWKS_NO_MATCHING_KEY";class as extends se{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}as.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class cs extends se{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}cs.code="ERR_JWKS_TIMEOUT";class ls extends se{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}ls.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function st(s,e){return s.name===e}function Xt(s){return parseInt(s.name.slice(4),10)}function no(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function io(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function oo(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!st(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Xt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!st(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Xt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!st(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Xt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!st(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!st(s.algorithm,"ECDSA"))throw we("ECDSA");const t=no(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}io(s,r)}function ds(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const us=(s,...e)=>ds("Key must be ",s,...e);function hs(s,e,...r){return ds(`Key for the ${s} algorithm must be `,e,...r)}const ps=s=>is(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",vt=["CryptoKey"],ao=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function co(s){return typeof s=="object"&&s!==null}function Se(s){if(!co(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const lo=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function qe(s){return Se(s)&&typeof s.kty=="string"}function uo(s){return s.kty!=="oct"&&typeof s.d=="string"}function ho(s){return s.kty!=="oct"&&typeof s.d>"u"}function po(s){return qe(s)&&s.kty==="oct"&&typeof s.k=="string"}function _o(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const _s=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=_o(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,zt.subtle.importKey("jwk",n,...t)},fs=s=>Ce(s);let ze,Je;const gs=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",Et=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await _s({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},fo={normalizePublicKey:(s,e)=>{if(gs(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?fs(r.k):(Je||(Je=new WeakMap),Et(Je,s,r,e))}return qe(s)?s.k?Ce(s.k):(Je||(Je=new WeakMap),Et(Je,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(gs(s)){let r=s.export({format:"jwk"});return r.k?fs(r.k):(ze||(ze=new WeakMap),Et(ze,s,r,e))}return qe(s)?s.k?Ce(s.k):(ze||(ze=new WeakMap),Et(ze,s,s,e,!0)):s}};async function xs(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Ce(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return _s({...s,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const je=s=>s==null?void 0:s[Symbol.toStringTag],Zt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},go=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&qe(e)){if(po(e)&&Zt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ps(e))throw new TypeError(hs(s,e,...vt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${je(e)} instances for symmetric algorithms must be of type "secret"`)}},xo=(s,e,r,t)=>{if(t&&qe(e))switch(r){case"sign":if(uo(e)&&Zt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ho(e)&&Zt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ps(e))throw new TypeError(hs(s,e,...vt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${je(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${je(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${je(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${je(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${je(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function ws(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?go(e,r,t,s):xo(e,r,t,s)}ws.bind(void 0,!1);const ms=ws.bind(void 0,!0);function wo(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const mo=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function yo(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function bo(s,e,r){if(e=await fo.normalizePublicKey(e,s),is(e))return oo(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(us(e,...vt));return zt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(us(e,...vt,"Uint8Array","JSON Web Key"))}const So=async(s,e,r,t)=>{const n=await bo(s,e,"verify");lo(s,n);const i=yo(s,n.algorithm);try{return await zt.subtle.verify(i,n,r,t)}catch{return!1}};async function vo(s,e,r){if(!Se(s))throw new re("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new re('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new re("JWS Protected Header incorrect type");if(s.payload===void 0)throw new re("JWS Payload missing");if(typeof s.signature!="string")throw new re("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new re("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const m=Ce(s.protected);t=JSON.parse(rt.decode(m))}catch{throw new re("JWS Protected Header is invalid")}if(!ao(t,s.header))throw new re("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=wo(re,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new re('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new re('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&mo("algorithms",r.algorithms);if(c&&!c.has(a))throw new os('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new re("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new re("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,ms(a,e,"verify"),qe(e)&&(e=await xs(e,a))):ms(a,e,"verify");const d=Qi(St.encode(s.protected??""),St.encode("."),typeof s.payload=="string"?St.encode(s.payload):s.payload);let p;try{p=Ce(s.signature)}catch{throw new re("Failed to base64url decode the signature")}if(!await So(a,e,p,d))throw new ls;let g;if(o)try{g=Ce(s.payload)}catch{throw new re("Failed to base64url decode the payload")}else typeof s.payload=="string"?g=St.encode(s.payload):g=s.payload;const w={payload:g};return s.protected!==void 0&&(w.protectedHeader=t),s.header!==void 0&&(w.unprotectedHeader=s.header),l?{...w,key:e}:w}async function Eo(s,e,r){if(s instanceof Uint8Array&&(s=rt.decode(s)),typeof s!="string")throw new re("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new re("Invalid Compact JWS");const a=await vo({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Io=s=>Math.floor(s.getTime()/1e3),ys=60,bs=ys*60,Qt=bs*24,Ao=Qt*7,To=Qt*365.25,Ro=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ss=s=>{const e=Ro.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*ys);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*bs);break;case"day":case"days":case"d":n=Math.round(r*Qt);break;case"week":case"weeks":case"w":n=Math.round(r*Ao);break;default:n=Math.round(r*To);break}return e[1]==="-"||e[4]==="ago"?-n:n},vs=s=>s.toLowerCase().replace(/^application\//,""),No=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Co=(s,e,r={})=>{let t;try{t=JSON.parse(rt.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||vs(s.typ)!==vs(n)))throw new pe('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),o!==void 0&&d.push("iss");for(const w of new Set(d.reverse()))if(!(w in t))throw new pe(`missing required "${w}" claim`,t,w,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new pe('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new pe('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!No(t.aud,typeof c=="string"?[c]:c))throw new pe('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=Ss(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=r,g=Io(f||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new pe('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new pe('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>g+p)throw new pe('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new pe('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=g-p)throw new Jt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const w=g-t.iat,m=typeof l=="number"?l:Ss(l);if(w-p>m)throw new Jt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(w<0-p)throw new pe('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Oo(s,e,r){var o;const t=await Eo(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:Co(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function ko(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function Po(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Do)}function Do(s){return Se(s)}function Es(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Lo{constructor(e){if(this._cached=new WeakMap,!Po(e))throw new jt("JSON Web Key Set malformed");this._jwks=Es(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=ko(t),o=this._jwks.keys.filter(l=>{let d=i===l.kty;if(d&&typeof n=="string"&&(d=n===l.kid),d&&typeof l.alg=="string"&&(d=t===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(t){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":d=l.crv==="Ed25519";break;case"EdDSA":d=l.crv==="Ed25519"||l.crv==="Ed448";break}return d}),{0:a,length:c}=o;if(c===0)throw new Yt;if(c!==1){const l=new as,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await Is(d,p,t)}catch{}},l}return Is(this._cached,a,t)}}async function Is(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await xs({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new jt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function As(s){const e=new Lo(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Es(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Bo=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new cs:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new se("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new se("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Mo(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let er;(typeof navigator>"u"||!((Fn=(Mt=navigator.userAgent)==null?void 0:Mt.startsWith)!=null&&Fn.call(Mt,"Mozilla/5.0 ")))&&(er="jose/v5.10.0");const tr=Symbol();function $o(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Uo{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[tr])!==void 0&&(this._cache=r==null?void 0:r[tr],$o(r==null?void 0:r[tr],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=As(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Yt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Mo()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);er&&!e.has("User-Agent")&&(e.set("User-Agent",er),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Bo(this._url,this._timeoutDuration,this._options).then(r=>{this._local=As(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Fo(s,e){const r=new Uo(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Wo=Ce;function Ho(s){if(typeof s!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=Wo(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(rt.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rr(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function ee(s,e,r=""){const t=rr(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 Ts(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Ye(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 Rs(s,e){ee(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 Go(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Xe(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function sr(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const Ko=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Vo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function qo(s){for(let e=0;e<s.length;e++)s[e]=Vo(s[e]);return s}const Ns=Ko?s=>s:qo,Cs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zo=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function nt(s){if(ee(s),Cs)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=zo[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Os(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function It(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Cs)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=Os(s.charCodeAt(i)),a=Os(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 Oe(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];ee(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 ks(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 Ps(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 Jo=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function jo(s,e,r){return s&e^~s&r}function Yo(s,e,r){return s&e^s&r^e&r}class Xo{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=sr(this.buffer)}update(e){Ye(this),ee(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=sr(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){Ye(this),Rs(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Xe(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=sr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[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 ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),At=BigInt(2**32-1),Ds=BigInt(32);function Zo(s,e=!1){return e?{h:Number(s&At),l:Number(s>>Ds&At)}:{h:Number(s>>Ds&At)|0,l:Number(s&At)|0}}function Qo(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}=Zo(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const ea=(s,e,r)=>s<<r|e>>>32-r,ta=(s,e,r)=>e<<r|s>>>32-r,ra=(s,e,r)=>e<<r-32|s>>>64-r,sa=(s,e,r)=>s<<r-32|e>>>64-r,na=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]),Pe=new Uint32Array(64);class ia extends Xo{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)Pe[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const f=Pe[p-15],g=Pe[p-2],w=me(f,7)^me(f,18)^f>>>3,m=me(g,17)^me(g,19)^g>>>10;Pe[p]=m+Pe[p-7]+w+Pe[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){const f=me(a,6)^me(a,11)^me(a,25),g=d+f+jo(a,c,l)+na[p]+Pe[p]|0,m=(me(t,2)^me(t,13)^me(t,22))+Yo(t,n,i)|0;d=l,l=c,c=a,a=o+g|0,o=i,i=n,n=t,t=g+m|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,d=d+this.H|0,this.set(t,n,i,o,a,c,l,d)}roundClean(){Xe(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Xe(this.buffer)}}class oa extends ia{constructor(){super(32);P(this,"A",ke[0]|0);P(this,"B",ke[1]|0);P(this,"C",ke[2]|0);P(this,"D",ke[3]|0);P(this,"E",ke[4]|0);P(this,"F",ke[5]|0);P(this,"G",ke[6]|0);P(this,"H",ke[7]|0)}}const aa=ks(()=>new oa,Jo(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nr=BigInt(0),ir=BigInt(1);function Tt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Ls(s){if(typeof s=="bigint"){if(!Ct(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function Rt(s){const e=Ls(s).toString(16);return e.length&1?"0"+e:e}function Bs(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?nr:BigInt("0x"+s)}function Nt(s){return Bs(nt(s))}function Ms(s){return Bs(nt(ca(ee(s)).reverse()))}function or(s,e){ve(e),s=Ls(s);const r=It(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function $s(s,e){return or(s,e).reverse()}function ca(s){return Uint8Array.from(s)}const Ct=s=>typeof s=="bigint"&&nr<=s;function la(s,e,r){return Ct(s)&&Ct(e)&&Ct(r)&&e<=s&&s<r}function da(s,e,r,t){if(!la(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function ua(s){let e;for(e=0;s>nr;s>>=ir,e+=1);return e}const ar=s=>(ir<<BigInt(s))-ir;function ha(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=x=>new Uint8Array(x),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),d=0;const p=()=>{c.fill(1),l.fill(0),d=0},f=(...x)=>r(l,Oe(c,...x)),g=(x=n)=>{l=f(i,x),c=f(),x.length!==0&&(l=f(o,x),c=f())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let x=0;const S=[];for(;x<e;){c=f();const I=c.slice();S.push(I),x+=c.length}return Oe(...S)};return(x,S)=>{p(),g(x);let I;for(;!(I=S(w()));)g();return p(),I}}function cr(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 Us(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 ae=BigInt(0),oe=BigInt(1),Be=BigInt(2),Fs=BigInt(3),Ws=BigInt(4),Hs=BigInt(5),pa=BigInt(7),Gs=BigInt(8),_a=BigInt(9),Ks=BigInt(16);function _e(s,e){const r=s%e;return r>=ae?r:e+r}function ue(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function Vs(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=_e(s,e),t=e,n=ae,i=oe;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==oe)throw new Error("invert: does not exist");return _e(n,e)}function lr(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function qs(s,e){const r=(s.ORDER+oe)/Ws,t=s.pow(e,r);return lr(s,t,e),t}function fa(s,e){const r=(s.ORDER-Hs)/Gs,t=s.mul(e,Be),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Be),n),a=s.mul(i,s.sub(o,s.ONE));return lr(s,a,e),a}function ga(s){const e=Ot(s),r=zs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+pa)/Ks;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,t);const p=a.mul(l,n),f=a.mul(l,i),g=a.eql(a.sqr(d),c),w=a.eql(a.sqr(p),c);l=a.cmov(l,d,g),d=a.cmov(f,p,w);const m=a.eql(a.sqr(d),c),x=a.cmov(l,d,m);return lr(a,x,c),x}}function zs(s){if(s<Fs)throw new Error("sqrt is not defined for small field");let e=s-oe,r=0;for(;e%Be===ae;)e/=Be,r++;let t=Be;const n=Ot(s);for(;js(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return qs;let i=n.pow(t,e);const o=(e+oe)/Be;return function(c,l){if(c.is0(l))return l;if(js(c,l)!==1)throw new Error("Cannot find square root");let d=r,p=c.mul(c.ONE,i),f=c.pow(l,e),g=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let w=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(w++,m=c.sqr(m),w===d)throw new Error("Cannot find square root");const x=oe<<BigInt(d-w-1),S=c.pow(p,x);d=w,p=c.sqr(S),f=c.mul(f,p),g=c.mul(g,S)}return g}}function xa(s){return s%Ws===Fs?qs:s%Gs===Hs?fa:s%Ks===_a?ga(s):zs(s)}const wa=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ma(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=wa.reduce((t,n)=>(t[n]="function",t),e);return cr(s,r),s}function ya(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===oe)return e;let t=s.ONE,n=e;for(;r>ae;)r&oe&&(t=s.mul(t,n)),n=s.sqr(n),r>>=oe;return t}function Js(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 js(s,e){const r=(s.ORDER-oe)/Be,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 ba(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Sa{constructor(e,r={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ae);P(this,"ONE",oe);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=ae)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}=ba(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 _e(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&oe)===oe}neg(e){return _e(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return _e(e*e,this.ORDER)}add(e,r){return _e(e+r,this.ORDER)}sub(e,r){return _e(e-r,this.ORDER)}mul(e,r){return _e(e*r,this.ORDER)}pow(e,r){return ya(this,e,r)}div(e,r){return _e(e*Vs(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 Vs(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=xa(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?$s(e,this.BYTES):or(e,this.BYTES)}fromBytes(e,r=!1){ee(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?Ms(e):Nt(e);if(a&&(c=_e(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Js(this,e)}cmov(e,r,t){return t?r:e}}function Ot(s,e={}){return new Sa(s,e)}function Ys(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 Xs(s){const e=Ys(s);return e+Math.ceil(e/2)}function va(s,e,r=!1){ee(s);const t=s.length,n=Ys(e),i=Xs(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?Ms(s):Nt(s),a=_e(o,e-oe)+oe;return r?$s(a,n):or(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ze=BigInt(0),Me=BigInt(1);function kt(s,e){const r=e.negate();return s?r:e}function Zs(s,e){const r=Js(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Qs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function dr(s,e){Qs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=ar(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function en(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+=Me);const l=e*t,d=l+Math.abs(a)-1,p=a===0,f=a<0,g=e%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:f,isNegF:g,offsetF:l}}const ur=new WeakMap,tn=new WeakMap;function hr(s){return tn.get(s)||1}function rn(s){if(s!==Ze)throw new Error("invalid wNAF")}class Ea{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>Ze;)r&Me&&(t=t.add(n)),n=n.double(),r>>=Me;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=dr(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=dr(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:f,offsetF:g}=en(t,a,o);t=c,d?i=i.add(kt(f,r[g])):n=n.add(kt(p,r[l]))}return rn(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=dr(e,this.bits);for(let o=0;o<i.windows&&t!==Ze;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=en(t,o,i);if(t=a,!l){const p=r[c];n=n.add(d?p.negate():p)}}return rn(t),n}getPrecomputes(e,r,t){let n=ur.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),ur.set(r,n))),n}cached(e,r,t){const n=hr(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=hr(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Qs(r,this.bits),tn.set(e,r),ur.delete(e)}hasCache(e){return hr(e)!==1}}function Ia(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ze||t>Ze;)r&Me&&(i=i.add(n)),t&Me&&(o=o.add(n)),n=n.double(),r>>=Me,t>>=Me;return{p1:i,p2:o}}function sn(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ma(e),e}else return Ot(s,{isLE:r})}function Aa(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>Ze))throw new Error(`CURVE.${c} must be positive bigint`)}const n=sn(e.p,r.Fp,t),i=sn(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 Ta(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class nn{constructor(e,r){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(Ts(e),ee(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),Xe(n)}update(e){return Ye(this),this.iHash.update(e),this}digestInto(e){Ye(this),ee(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 on=(s,e,r)=>new nn(s,e).update(r).digest();on.create=(s,e)=>new nn(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const an=(s,e)=>(s+(s>=0?e:-e)/cn)/e;function Ra(s,e,r){const[[t,n],[i,o]]=e,a=an(o*s,r),c=an(-n*s,r);let l=s-a*t-c*i,d=-a*n-c*o;const p=l<Ie,f=d<Ie;p&&(l=-l),f&&(d=-d);const g=ar(Math.ceil(ua(r)/2))+Qe;if(l<Ie||l>=g||d<Ie||d>=g)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:f,k2:d}}function pr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function _r(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return Tt(r.lowS,"lowS"),Tt(r.prehash,"prehash"),r.format!==void 0&&pr(r.format),r}class Na extends Error{constructor(e=""){super(e)}}const De={Err:Na,_tlv:{encode:(s,e)=>{const{Err:r}=De;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=Rt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?Rt(n.length/2|128):"";return Rt(s)+i+n+e},decode(s,e){const{Err:r}=De;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 d of l)o=o<<8|d;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}=De;if(s<Ie)throw new e("integer: negative integers are not allowed");let r=Rt(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}=De;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}=De,n=ee(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:d}=t.decode(2,c);if(d.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}=De,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Qe=BigInt(1),cn=BigInt(2),Pt=BigInt(3),Ca=BigInt(4);function Oa(s,e={}){const r=Aa("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;cr(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=dn(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(W,y,b){const{x:R,y:O}=y.toAffine(),$=t.toBytes(R);if(Tt(b,"isCompressed"),b){d();const B=!t.isOdd(O);return Oe(ln(B),$)}else return Oe(Uint8Array.of(4),$,t.toBytes(O))}function f(W){ee(W,void 0,"Point");const{publicKey:y,publicKeyUncompressed:b}=l,R=W.length,O=W[0],$=W.subarray(1);if(R===y&&(O===2||O===3)){const B=t.fromBytes($);if(!t.isValid(B))throw new Error("bad point: is not on curve, wrong x");const M=m(B);let k;try{k=t.sqrt(M)}catch(A){const N=A instanceof Error?": "+A.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}d();const V=t.isOdd(k);return(O&1)===1!==V&&(k=t.neg(k)),{x:B,y:k}}else if(R===b&&O===4){const B=t.BYTES,M=t.fromBytes($.subarray(0,B)),k=t.fromBytes($.subarray(B,B*2));if(!x(M,k))throw new Error("bad point: is not on curve");return{x:M,y:k}}else throw new Error(`bad point: got length ${R}, expected compressed=${y} or uncompressed=${b}`)}const g=e.toBytes||p,w=e.fromBytes||f;function m(W){const y=t.sqr(W),b=t.mul(y,W);return t.add(t.add(b,t.mul(W,i.a)),i.b)}function x(W,y){const b=t.sqr(y),R=m(W);return t.eql(b,R)}if(!x(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const S=t.mul(t.pow(i.a,Pt),Ca),I=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(S,I)))throw new Error("bad curve params: a or b");function U(W,y,b=!1){if(!t.isValid(y)||b&&t.is0(y))throw new Error(`bad point coordinate ${W}`);return y}function C(W){if(!(W instanceof z))throw new Error("Weierstrass Point expected")}function L(W){if(!c||!c.basises)throw new Error("no endo");return Ra(W,c.basises,n.ORDER)}const H=Us((W,y)=>{const{X:b,Y:R,Z:O}=W;if(t.eql(O,t.ONE))return{x:b,y:R};const $=W.is0();y==null&&(y=$?t.ONE:t.inv(O));const B=t.mul(b,y),M=t.mul(R,y),k=t.mul(O,y);if($)return{x:t.ZERO,y:t.ZERO};if(!t.eql(k,t.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),G=Us(W=>{if(W.is0()){if(e.allowInfinityPoint&&!t.is0(W.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:b}=W.toAffine();if(!t.isValid(y)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!x(y,b))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function q(W,y,b,R,O){return b=new z(t.mul(b.X,W),b.Y,b.Z),y=kt(R,y),b=kt(O,b),y.add(b)}const F=class F{constructor(y,b,R){P(this,"X");P(this,"Y");P(this,"Z");this.X=U("x",y),this.Y=U("y",b,!0),this.Z=U("z",R),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){const{x:b,y:R}=y||{};if(!y||!t.isValid(b)||!t.isValid(R))throw new Error("invalid affine point");if(y instanceof F)throw new Error("projective point not allowed");return t.is0(b)&&t.is0(R)?F.ZERO:new F(b,R,t.ONE)}static fromBytes(y){const b=F.fromAffine(w(ee(y,void 0,"point")));return b.assertValidity(),b}static fromHex(y){return F.fromBytes(It(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,b=!0){return D.createCache(this,y),b||this.multiply(Pt),this}assertValidity(){G(this)}hasEvenY(){const{y}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(y)}equals(y){C(y);const{X:b,Y:R,Z:O}=this,{X:$,Y:B,Z:M}=y,k=t.eql(t.mul(b,M),t.mul($,O)),V=t.eql(t.mul(R,M),t.mul(B,O));return k&&V}negate(){return new F(this.X,t.neg(this.Y),this.Z)}double(){const{a:y,b}=i,R=t.mul(b,Pt),{X:O,Y:$,Z:B}=this;let M=t.ZERO,k=t.ZERO,V=t.ZERO,E=t.mul(O,O),A=t.mul($,$),N=t.mul(B,B),T=t.mul(O,$);return T=t.add(T,T),V=t.mul(O,B),V=t.add(V,V),M=t.mul(y,V),k=t.mul(R,N),k=t.add(M,k),M=t.sub(A,k),k=t.add(A,k),k=t.mul(M,k),M=t.mul(T,M),V=t.mul(R,V),N=t.mul(y,N),T=t.sub(E,N),T=t.mul(y,T),T=t.add(T,V),V=t.add(E,E),E=t.add(V,E),E=t.add(E,N),E=t.mul(E,T),k=t.add(k,E),N=t.mul($,B),N=t.add(N,N),E=t.mul(N,T),M=t.sub(M,E),V=t.mul(N,A),V=t.add(V,V),V=t.add(V,V),new F(M,k,V)}add(y){C(y);const{X:b,Y:R,Z:O}=this,{X:$,Y:B,Z:M}=y;let k=t.ZERO,V=t.ZERO,E=t.ZERO;const A=i.a,N=t.mul(i.b,Pt);let T=t.mul(b,$),K=t.mul(R,B),J=t.mul(O,M),Z=t.add(b,R),j=t.add($,B);Z=t.mul(Z,j),j=t.add(T,K),Z=t.sub(Z,j),j=t.add(b,O);let Q=t.add($,M);return j=t.mul(j,Q),Q=t.add(T,J),j=t.sub(j,Q),Q=t.add(R,O),k=t.add(B,M),Q=t.mul(Q,k),k=t.add(K,J),Q=t.sub(Q,k),E=t.mul(A,j),k=t.mul(N,J),E=t.add(k,E),k=t.sub(K,E),E=t.add(K,E),V=t.mul(k,E),K=t.add(T,T),K=t.add(K,T),J=t.mul(A,J),j=t.mul(N,j),K=t.add(K,J),J=t.sub(T,J),J=t.mul(A,J),j=t.add(j,J),T=t.mul(K,j),V=t.add(V,T),T=t.mul(Q,j),k=t.mul(Z,k),k=t.sub(k,T),T=t.mul(Z,K),E=t.mul(Q,E),E=t.add(E,T),new F(k,V,E)}subtract(y){return this.add(y.negate())}is0(){return this.equals(F.ZERO)}multiply(y){const{endo:b}=e;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let R,O;const $=B=>D.cached(this,B,M=>Zs(F,M));if(b){const{k1neg:B,k1:M,k2neg:k,k2:V}=L(y),{p:E,f:A}=$(M),{p:N,f:T}=$(V);O=A.add(T),R=q(b.beta,E,N,B,k)}else{const{p:B,f:M}=$(y);R=B,O=M}return Zs(F,[R,O])[0]}multiplyUnsafe(y){const{endo:b}=e,R=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Ie||R.is0())return F.ZERO;if(y===Qe)return R;if(D.hasCache(this))return this.multiply(y);if(b){const{k1neg:O,k1:$,k2neg:B,k2:M}=L(y),{p1:k,p2:V}=Ia(F,R,$,M);return q(b.beta,k,V,O,B)}else return D.unsafe(R,y)}toAffine(y){return H(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Qe?!0:y?y(F,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Qe?this:y?y(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return Tt(y,"isCompressed"),this.assertValidity(),g(F,this,y)}toHex(y=!0){return nt(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(F,"BASE",new F(i.Gx,i.Gy,t.ONE)),P(F,"ZERO",new F(t.ZERO,t.ONE,t.ZERO)),P(F,"Fp",t),P(F,"Fn",n);let z=F;const ne=n.BITS,D=new Ea(z,e.endo?Math.ceil(ne/2):ne);return z.BASE.precompute(8),z}function ln(s){return Uint8Array.of(s?2:3)}function dn(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ka(s,e={}){const{Fn:r}=s,t=e.randomBytes||Ps,n=Object.assign(dn(s.Fp,r),{seed:Xs(r.ORDER)});function i(g){try{const w=r.fromBytes(g);return r.isValidNot0(w)}catch{return!1}}function o(g,w){const{publicKey:m,publicKeyUncompressed:x}=n;try{const S=g.length;return w===!0&&S!==m||w===!1&&S!==x?!1:!!s.fromBytes(g)}catch{return!1}}function a(g=t(n.seed)){return va(ee(g,n.seed,"seed"),r.ORDER)}function c(g,w=!0){return s.BASE.multiply(r.fromBytes(g)).toBytes(w)}function l(g){const{secretKey:w,publicKey:m,publicKeyUncompressed:x}=n;if(!rr(g)||"_lengths"in r&&r._lengths||w===m)return;const S=ee(g,void 0,"key").length;return S===m||S===x}function d(g,w,m=!0){if(l(g)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const x=r.fromBytes(g);return s.fromBytes(w).multiply(x).toBytes(m)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},f=Ta(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:f,Point:s,utils:p,lengths:n})}function Pa(s,e,r={}){Ts(e),cr(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Ps,n=r.hmac||((y,b)=>on(e,y,b)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:p,utils:f,lengths:g}=ka(s,r),w={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},m=a*cn<i.ORDER;function x(y){const b=a>>Qe;return y>b}function S(y,b){if(!o.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function I(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(y,b){pr(b);const R=g.signature,O=b==="compact"?R:b==="recovered"?R+1:void 0;return ee(y,O)}class C{constructor(b,R,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=S("r",b),this.s=S("s",R),O!=null){if(I(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(b,R=w.format){U(b,R);let O;if(R==="der"){const{r:k,s:V}=De.toSig(ee(b));return new C(k,V)}R==="recovered"&&(O=b[0],R="compact",b=b.subarray(1));const $=g.signature/2,B=b.subarray(0,$),M=b.subarray($,$*2);return new C(o.fromBytes(B),o.fromBytes(M),O)}static fromHex(b,R){return this.fromBytes(It(b),R)}assertRecovery(){const{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new C(this.r,this.s,b)}recoverPublicKey(b){const{r:R,s:O}=this,$=this.assertRecovery(),B=$===2||$===3?R+a:R;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes(B),k=s.fromBytes(Oe(ln(($&1)===0),M)),V=o.inv(B),E=H(ee(b,void 0,"msgHash")),A=o.create(-E*V),N=o.create(O*V),T=s.BASE.multiplyUnsafe(A).add(k.multiplyUnsafe(N));if(T.is0())throw new Error("invalid recovery: point at infinify");return T.assertValidity(),T}hasHighS(){return x(this.s)}toBytes(b=w.format){if(pr(b),b==="der")return It(De.hexFromSig(this));const{r:R,s:O}=this,$=o.toBytes(R),B=o.toBytes(O);return b==="recovered"?(I(),Oe(Uint8Array.of(this.assertRecovery()),$,B)):Oe($,B)}toHex(b){return nt(this.toBytes(b))}}const L=r.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const R=Nt(b),O=b.length*8-c;return O>0?R>>BigInt(O):R},H=r.bits2int_modN||function(b){return o.create(L(b))},G=ar(c);function q(y){return da("num < 2^"+c,y,Ie,G),o.toBytes(y)}function z(y,b){return ee(y,void 0,"message"),b?ee(e(y),void 0,"prehashed message"):y}function ne(y,b,R){const{lowS:O,prehash:$,extraEntropy:B}=_r(R,w);y=z(y,$);const M=H(y),k=o.fromBytes(b);if(!o.isValidNot0(k))throw new Error("invalid private key");const V=[q(k),q(M)];if(B!=null&&B!==!1){const T=B===!0?t(g.secretKey):B;V.push(ee(T,void 0,"extraEntropy"))}const E=Oe(...V),A=M;function N(T){const K=L(T);if(!o.isValidNot0(K))return;const J=o.inv(K),Z=s.BASE.multiply(K).toAffine(),j=o.create(Z.x);if(j===Ie)return;const Q=o.create(J*o.create(A+j*k));if(Q===Ie)return;let Fe=(Z.x===j?0:2)|Number(Z.y&Qe),Wn=Q;return O&&x(Q)&&(Wn=o.neg(Q),Fe^=1),new C(j,Wn,m?void 0:Fe)}return{seed:E,k2sig:N}}function D(y,b,R={}){const{seed:O,k2sig:$}=ne(y,b,R);return ha(e.outputLen,o.BYTES,n)(O,$).toBytes(R.format)}function F(y,b,R,O={}){const{lowS:$,prehash:B,format:M}=_r(O,w);if(R=ee(R,void 0,"publicKey"),b=z(b,B),!rr(y)){const k=y instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+k)}U(y,M);try{const k=C.fromBytes(y,M),V=s.fromBytes(R);if($&&k.hasHighS())return!1;const{r:E,s:A}=k,N=H(b),T=o.inv(A),K=o.create(N*T),J=o.create(E*T),Z=s.BASE.multiplyUnsafe(K).add(V.multiplyUnsafe(J));return Z.is0()?!1:o.create(Z.x)===E}catch{return!1}}function W(y,b,R={}){const{prehash:O}=_r(R,w);return b=z(b,O),C.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:p,utils:f,lengths:g,Point:s,sign:D,verify:F,recoverPublicKey:W,Signature:C,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Da={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},un=BigInt(2);function La(s){const e=fr.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,d=l*l*s%e,p=ue(d,r,e)*d%e,f=ue(p,r,e)*d%e,g=ue(f,un,e)*l%e,w=ue(g,n,e)*g%e,m=ue(w,i,e)*w%e,x=ue(m,a,e)*m%e,S=ue(x,c,e)*x%e,I=ue(S,a,e)*m%e,U=ue(I,r,e)*d%e,C=ue(U,o,e)*w%e,L=ue(C,t,e)*l%e,H=ue(L,un,e);if(!gr.eql(gr.sqr(H),s))throw new Error("Cannot find square root");return H}const gr=Ot(fr.p,{sqrt:La}),Ba=Pa(Oa(fr,{Fp:gr,endo:Da}),aa),Ma=BigInt(0),it=BigInt(1),$a=BigInt(2),Ua=BigInt(7),Fa=BigInt(256),Wa=BigInt(113),hn=[],pn=[],_n=[];for(let s=0,e=it,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],hn.push(2*(5*t+r)),pn.push((s+1)*(s+2)/2%64);let n=Ma;for(let i=0;i<7;i++)e=(e<<it^(e>>Ua)*Wa)%Fa,e&$a&&(n^=it<<(it<<BigInt(i))-it);_n.push(n)}const fn=Qo(_n,!0),Ha=fn[0],Ga=fn[1],gn=(s,e,r)=>r>32?ra(s,e,r):ea(s,e,r),xn=(s,e,r)=>r>32?sa(s,e,r):ta(s,e,r);function Ka(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],d=r[c+1],p=gn(l,d,1)^r[a],f=xn(l,d,1)^r[a+1];for(let g=0;g<50;g+=10)s[o+g]^=p,s[o+g+1]^=f}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=pn[o],c=gn(n,i,a),l=xn(n,i,a),d=hn[o];n=s[d],i=s[d+1],s[d]=c,s[d+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]^=Ha[t],s[1]^=Ga[t]}Xe(r)}class xr{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,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Go(this.state)}clone(){return this._cloneInto()}keccak(){Ns(this.state32),Ka(this.state32,this.rounds),Ns(this.state32),this.posOut=0,this.pos=0}update(e){Ye(this),ee(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)!==0&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ye(this,!1),ee(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 ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rs(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,Xe(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new xr(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 wn=((s,e,r,t={})=>ks(()=>new xr(e,s,r),t))(1,136,32),Va=60;class qa{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Fo(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Va<n)return u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Oo(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};u.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ho(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=wn(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=za(a),l=c.slice(0,32),d=c.slice(32,64),p=c[64],f=p>=27?p-27:p,m=new Ba.Signature(mn(l),mn(d)).addRecoveryBit(f).recoverPublicKey(o).toBytes(!1).slice(1),x=wn(m);return"0x"+nt(x.slice(12))}}function za(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 mn(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Ja=5e3;class ja{constructor(e,r){this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyInFlight=null,this.keyFailedAt=0,this.required=!1,this.adapterConfig=e,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async seal(e){if(!e)return e;const r=this.required;if(!r&&this.hasFreshFailure())return e;try{const{version:t,key:n}=await this.currentKey(),i=await Ya(n,e);return`${t}.${Xa(i)}`}catch(t){if(r)throw this.keyFailedAt=Date.now(),t instanceof _?t:new _(h.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(t)});return this.keyFailedAt=Date.now(),u.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(Br/1e3)}초 후 재확인)`),e}}invalidate(){u.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(u.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.currentKey().then(()=>{},()=>{})}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<Br}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<Jn?{version:this.cachedVersion,key:this.cachedKey}:this.keyInFlight?this.keyInFlight:(this.keyInFlight=this.fetchAndImportKey().then(e=>(this.cachedVersion=e.version,this.cachedKey=e.key,this.cachedAt=Date.now(),this.keyFailedAt=0,u.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=yn();if(!e)throw new _(h.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다. HTTPS 환경에서 다시 시도해 주세요.");const r=await this.transport.request({url:`${this.baseUrl}/pin-key`,method:"GET",headers:{"X-Project-Id":this.adapterConfig.projectId},timeoutMs:Ja}),t=tc(r.data);if(!(t!=null&&t.keyVersion)||!(t!=null&&t.publicKey))throw new _(h.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const n=Qa(t.publicKey),i=await e.importKey("spki",ec(n),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:t.keyVersion,key:i}}}async function Ya(s,e){const r=yn();if(!r)throw new _(h.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const t=await r.encrypt({name:"RSA-OAEP"},s,new TextEncoder().encode(e));return new Uint8Array(t)}function yn(){const s=globalThis.crypto;return(s==null?void 0:s.subtle)??null}function Xa(s){return Za(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Za(s){let e="";for(let r=0;r<s.length;r+=3){const t=s[r],n=s[r+1],i=s[r+2];e+=ot[t>>2],e+=ot[(t&3)<<4|(n??0)>>4],e+=n===void 0?"=":ot[(n&15)<<2|(i??0)>>6],e+=i===void 0?"=":ot[i&63]}return e}function Qa(s){const e=s.replace(/-----BEGIN [A-Z ]+-----/g,"").replace(/-----END [A-Z ]+-----/g,"").replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?e:e+"=".repeat(4-e.length%4),t=[];for(let n=0;n<r.length;n+=4){const i=[0,1,2,3].map(o=>{const a=r[n+o];if(a==="="||a===void 0)return-1;const c=ot.indexOf(a);if(c===-1)throw new _(h.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return c});t.push((i[0]&63)<<2|(i[1]&63)>>4),i[2]!==-1&&t.push((i[1]&15)<<4|(i[2]&63)>>2),i[3]!==-1&&t.push((i[2]&3)<<6|i[3]&63)}return new Uint8Array(t)}function ec(s){const e=new Uint8Array(s.length);return e.set(s),e.buffer}function tc(s){if(!s||typeof s!="object")return null;const e=s;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new _(h.PIN_ENCRYPTION_FAILED,`pin-key 조회 실패 (${e.code}): ${String(e.message??e.data??"")}`);const r=e.data;if(r&&typeof r=="object")return r}return typeof e.keyVersion=="string"&&typeof e.publicKey=="string"?e:null}const rc=3e4,sc=1e3;class nc{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,sc*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??rc);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)}}}function ic(s){const e={raw:s},r=s.search(/(^|;)\s*info=/i),t=r>=0?s.slice(0,r):s;if(r>=0){const n=s.slice(r).replace(/^;?\s*info=/i,"").trim();n&&(e.infoUrl=n)}for(const n of t.split(";")){const[i,...o]=n.split("=");if((i==null?void 0:i.trim().toLowerCase())==="sunset"){const a=o.join("=").trim();a&&(e.sunset=a)}}return e}function bn(s){try{return new URL(s).origin}catch{return null}}class oc{constructor(e,r){this.inner=e,this.options=r}async request(e){if(!this.isGateway(e.url))return this.inner.request(e);const r=await this.inner.request(this.options.sendVersionHeader===!1?e:{...e,headers:{...e.headers,[jn]:this.options.version}});return this.inspect(r),r}isGateway(e){const r=bn(e);return r===null?!1:this.options.getGatewayBaseUrls().some(t=>bn(t)===r)}inspect(e){var n,i,o,a;const r=ac(e.headers,Xn);r&&((i=(n=this.options).onDeprecation)==null||i.call(n,ic(r)));const t=e.data;t&&t.code===ht&&((a=(o=this.options).onUnsupported)==null||a.call(o,{message:typeof t.message=="string"?t.message:void 0}))}}function ac(s,e){if(!s)return;const r=e.toLowerCase();for(const[t,n]of Object.entries(s))if(t.toLowerCase()===r&&n)return n}const cc=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function wr(){return typeof window>"u"?void 0:window}function lc(){const s=wr();return s==null?void 0:s.__crossx}function dc(s){return s==="ios"||s==="android"?s:null}function mr(){const s=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(s)?"android":/iPhone|iPad|iPod|Macintosh/i.test(s)?"ios":null}function uc(s,e){const r=o=>o.split(/[^\d]+/).filter(a=>a!=="").map(a=>Number.parseInt(a,10)),t=r(s),n=r(e),i=Math.max(t.length,n.length);for(let o=0;o<i;o+=1){const a=(t[o]??0)-(n[o]??0);if(a!==0)return a}return 0}function hc(){const s=wr();if(!s)return!1;const e=s.__crossxRNBridge;return e!=null&&e.isInstalled?!0:s.__CROSSX_BRIDGE_INITIALIZED__===!0||s.__CROSSX_RN_BRIDGE_READY__===!0}function Sn(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of cc){const r=e.exec(s);if(r)return r[1]??null}}function at(){const s=lc();if(s!=null&&s.browser)return{version:s.version??null,platform:dc(s.platform)??mr(),detectedBy:"marker"};if(hc())return{version:Sn()??null,platform:mr(),detectedBy:"bridge"};const e=Sn();return e!==void 0?{version:e,platform:mr(),detectedBy:"user-agent"}:null}function pc(){return at()!==null}function _c(s=3e3){const e=at();return e?Promise.resolve(e):wr()?new Promise(r=>{const t=Date.now(),n=setInterval(()=>{const i=at();if(i){clearInterval(n),r(i);return}Date.now()-t>=s&&(clearInterval(n),r(null))},50)}):Promise.resolve(null)}const fc=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io","https://one-wallet-oauth.onechain.nexus","https://stg-one-wallet-oauth.onechain.nexus","https://dev-one-wallet-oauth.onechain.nexus"]),gc="crossx://oauth-callback",xc="2.3.2";function wc(s){return s.platform!=="ios"?!1:s.version?uc(s.version,xc)<=0:!0}class $e{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(u.log("[CROSSx] OAuth 대기 중단 —",e),r(e))}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=$e.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){u.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await $e.sha256Hex(r);if(u.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(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.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=$e.generateRandom16Hex(),l=$e.generateRandom16Hex(),d=at();let p=e.authUrl;d&&e.legacyAuthUrl&&wc(d)&&(p=e.legacyAuthUrl,u.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:d.version??"(unknown)",detectedBy:d.detectedBy,authUrlBase:e.legacyAuthUrl}));const f=p.includes("?")?"&":"?",g=encodeURIComponent(window.location.origin);let w=`${p}${f}state=${c}&nonce=${l}&origin=${g}`;d&&!w.includes("redirectUrl=")&&(w+=`&redirectUrl=${encodeURIComponent(gc)}`,u.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:d.detectedBy,appVersion:d.version??"(unknown)",platform:d.platform??"(unknown)"})),u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:p});const m=window.open(w,d?"_blank":"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!m){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const x=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),G(),t(new Error("Authentication timeout"))},300*1e3),S=10,I=30;let U=0,C=null;const L=()=>{clearInterval(H),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+I+"초간 대기합니다"),C=setTimeout(()=>{G(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},I*1e3)},H=setInterval(()=>{U++;try{if(!m.closed)return;if(!!d){G(),t(new _(h.USER_REJECTED,"로그인이 취소되었습니다"));return}const ne=typeof document<"u"&&document.hasFocus();U<=S&&!ne?L():(G(),t(new _(h.USER_REJECTED,"로그인이 취소되었습니다")))}catch{L()}},1e3),G=()=>{this.abortPending=null,clearTimeout(x),clearInterval(H),C&&clearTimeout(C),window.removeEventListener("message",q)},q=z=>{if(!fc.has(z.origin))return;G();const ne=typeof z.data.status=="string",D=ne?z.data.data??{}:z.data;u.log("[CROSSx] OAuth postMessage 수신 —",{format:ne?"wrapped":"flat",status:ne?z.data.status:"(flat)"});const F=(D==null?void 0:D.state)??z.data.state;if(!F||F!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ne&&z.data.status!=="success"){u.error("[CROSSx] OAuth 실패:",D==null?void 0:D.error),t(new Error((D==null?void 0:D.error)||"Authentication failed"));return}if(!ne&&(D!=null&&D.error)){u.error("[CROSSx] OAuth 실패:",D.error),t(new Error(D.error||"Authentication failed"));return}const W=D==null?void 0:D.idToken,y=D==null?void 0:D.accessToken,b=y??W,R=(D==null?void 0:D.email)||void 0;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!y,hasIdToken:!!W,hasEmail:!!R}),!b){u.error("[CROSSx] 토큰을 찾을 수 없음:",z.data),t(new Error("Token not found in response"));return}const O={token:b,email:R},$=B=>{$e.verifyIdTokenNonce(B,l).then(()=>r(O)).catch(M=>{u.error("[CROSSx] nonce 검증 실패:",M),t(M instanceof Error?M:new Error("nonce verification failed"))})};y?y.split(".").length===3?$(y):W?$(W):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(O)):W?$(W):t(new Error("Token not found in response"))};this.abortPending=z=>{G(),t(new Error(z))},window.addEventListener("message",q)})}}const ct="crossx_wallet_data",et="crossx_mock_pin_hash";class mc{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(ct)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(ct);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(ct,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(et,i),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new _(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(ct);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 u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return u.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 u.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){u.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 u.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(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(et);return r&&r!==e?!1:(r||await this.storage.set(et,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new _(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(et);if(n&&t&&n!==t)throw new _(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(et,r),u.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(u.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new _(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 _(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(ct,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(et,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return u.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("")}}const yc=["password","newPassword","recoveryPin"];class Ue{constructor(e,r,t,n,i,o){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,this.pinEncryptor=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Lr))return e;const r=!e||this.tokenStore.isExpiringSoon(Lr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return u.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(u.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async sealPinFields(e){if(!this.pinEncryptor||!e||typeof e!="object")return e;let r=null;for(const t of yc){const n=e[t];if(typeof n!="string"||n==="")continue;const i=await this.pinEncryptor.seal(n);i!==n&&(r||(r={...e}),r[t]=i)}return r??e}async request(e,r,t,n=!1,i=!1){var d,p,f,g;const o=await this.ensureValidToken(),a=`${this.baseUrl}${r}`,c={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId},l=await this.sealPinFields(t);try{const m=(await this.transport.request({url:a,method:e,headers:c,body:l??void 0})).data;if(m&&typeof m.code=="number"){if(m.code<0||m.code>=400){const x=m.message||m.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:m.code,message:x,url:a,method:e});const S=Ue.mapGatewayError(m.code,m.data);if(S===h.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!i))return u.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,r,t,n,!0);if(S===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(u.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0,i);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(S===h.USER_NOT_FOUND)throw u.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(d=this._onUnauthorized)==null||d.call(this),new _(h.USER_NOT_FOUND,Ue.getGatewayErrorMessage(m.code,x));const I=S===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:S,U=I===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ue.getGatewayErrorMessage(m.code,x),C=m.data;let L;throw S===h.PIN_LOCKED?L=Ue.extractLockDetails(C):S===h.ADDRESS_LIMIT_EXCEEDED?L={limit:dt,raw:C}:L=C??void 0,new _(I,U,L)}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:m.code,url:a,method:e}),m.data??m}return m}catch(w){if(w instanceof _)throw w;const m=((p=w.response)==null?void 0:p.status)??w.status;if((m===401||m===403)&&!n&&this._onTokenRefresh){if(u.warn(`[CROSSx] HTTP ${m} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0,i);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((f=w.response)!=null&&f.data){const x=w.response.data,S=x.message||x.data||"API 요청에 실패했습니다",I=x.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:I,message:S,url:a,method:e,status:(g=w.response)==null?void 0:g.status}),new _(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${I}): ${S}`)}throw w}}async checkWallet(){var r,t;u.log("[CROSSx] GET /mnemonic/check"),(t=(r=this.pinEncryptor)==null?void 0:r.prewarm)==null||t.call(r);const e=await this.request("GET","/mnemonic/check");return u.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,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(h.MIGRATION_BACKUP_EXISTS,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.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 _(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new _(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 _(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){u.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 u.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 _(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 _(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 _(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 _(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 ht:return h.SDK_VERSION_UNSUPPORTED;case-10028:return Ue.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-10045:return h.PIN_ENCRYPTION_INVALID;case-10046:return h.PIN_POLICY_VIOLATION;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 ht:return`This SDK version is no longer supported. Update @nexus-cross/crossx-sdk-core.${r?` (${r})`:""}`;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 ${dt} accounts allowed.`;case-10045:return"Could not securely send your PIN. Please try again.";case-10046:return r||"This PIN does not meet the security policy. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class bc{constructor(e,r,t,n=()=>{},i=()=>{},o=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,this.getAppName=i,this.onBridgeUnauthorized=o,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(a,c)=>e.prepare(a,c)),e.migrateWallet&&(this.migrateWallet=(a,c)=>e.migrateWallet(a,c)),e.verifyPin&&(this.verifyPin=a=>e.verifyPin(a)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(a,c)=>e.verifyRecoveryPin(a,c))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async innerOwnsAddress(e,r){if(!r)return!0;try{return(await this.inner.getAddresses(e)).some(n=>n.address.toLowerCase()===r.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,r,t,n){return!Ur(e)||!await this.innerOwnsAddress(r,t)?!1:(this.onBridgeUnauthorized(`native 가 ${n} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();try{const c=await a.signMessage({chainId:r,message:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,o,"signMessage"))throw He(c,h.SIGNATURE_FAILED)}}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();try{const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,o,"signTypedData"))throw He(c,h.SIGNATURE_FAILED)}}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();try{const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}catch(a){if(!await this.recoverFromUnauthorized(a,e,t.from,"signTransaction"))throw He(a,h.SIGNATURE_FAILED)}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,dappName:this.getAppName()})).txHash}}catch(o){if(!await this.recoverFromUnauthorized(o,e,t.from,"sendTransaction"))throw He(o,h.TRANSACTION_FAILED)}}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 lt{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=lt.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?zn:qn;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 _(lt.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=lt.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new _(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(_t).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;case ht:return h.SDK_VERSION_UNSUPPORTED;default:return h.UNKNOWN_ERROR}}}const yr="linear(0, 0.0152, 0.0546, 0.1107, 0.1771, 0.2494, 0.3236, 0.3973, 0.4684, 0.5356, 0.598, 0.655, 0.7066, 0.7526, 0.7933, 0.829, 0.8599, 0.8865, 0.9092, 0.9283, 0.9443, 0.9576, 0.9685, 0.9774, 0.9845, 0.9901, 0.9945, 0.9979, 1.0004, 1.0022, 1.0035, 1.0043, 1.0048, 1.005, 1.005, 1.0049, 1.0046, 1.0043, 1.004, 1.0036, 1.0032, 1.0029, 1.0025, 1.0022, 1.0019, 1.0016, 1.0014, 1.0011, 1.0009, 1.0008, 1.0006)",Sc=['<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:28.16%;top:32.04%;width:0.96%;height:1%;--x0:64.9347px;--y0:44.2101px;--r0:46.0deg;--x1:-14.2856px;--y1:-9.7262px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="2.65719" height="2.63854" viewBox="0 0 2.65719 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.3286 2.63854C2.06236 2.63854 2.65719 2.04788 2.65719 1.31927C2.65719 0.590657 2.06236 0 1.3286 0C0.594835 0 0 0.590657 0 1.31927C0 2.04788 0.594835 2.63854 1.3286 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:16.05%;top:64.23%;width:0.97%;height:1%;--x0:98.3418px;--y0:-41.6939px;--r0:46.0deg;--x1:-21.6352px;--y1:9.1727px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="2.65719" height="2.63854" viewBox="0 0 2.65719 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.3286 2.63854C2.06236 2.63854 2.65719 2.04788 2.65719 1.31927C2.65719 0.590657 2.06236 0 1.3286 0C0.594835 0 0 0.590657 0 1.31927C0 2.04788 0.594835 2.63854 1.3286 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:40.21%;top:23.2%;width:1.11%;height:1.15%;--x0:31.463px;--y0:67.6121px;--r0:46.0deg;--x1:-6.9219px;--y1:-14.8747px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="3.06599" height="3.04447" viewBox="0 0 3.06599 3.04447" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.53299 3.04447C2.37964 3.04447 3.06599 2.36294 3.06599 1.52223C3.06599 0.681528 2.37964 0 1.53299 0C0.686344 0 0 0.681528 0 1.52223C0 2.36294 0.686344 3.04447 1.53299 3.04447Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:67.21%;top:39.57%;width:0.96%;height:1%;--x0:-42.8544px;--y0:24.1183px;--r0:-46.0deg;--x1:9.428px;--y1:-5.306px;--r1:11.0deg"><svg preserveAspectRatio="none" width="2.65718" height="2.63854" viewBox="0 0 2.65718 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.32858 2.63854C2.06234 2.63854 2.65718 2.04789 2.65718 1.31927C2.65718 0.59066 2.06234 0 1.32858 0C0.594819 0 0 0.59066 0 1.31927C0 2.04789 0.594819 2.63854 1.32858 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:79.86%;top:71.84%;width:0.96%;height:1%;--x0:-77.7582px;--y0:-62.0034px;--r0:-46.0deg;--x1:17.1068px;--y1:13.6407px;--r1:11.0deg"><svg preserveAspectRatio="none" width="2.65718" height="2.63854" viewBox="0 0 2.65718 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.32858 2.63854C2.06234 2.63854 2.65718 2.04789 2.65718 1.31927C2.65718 0.59066 2.06234 0 1.32858 0C0.594819 0 0 0.59066 0 1.31927C0 2.04789 0.594819 2.63854 1.32858 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:23.14%;top:35.69%;width:3.75%;height:3.88%;--x0:74.93px;--y0:30.6249px;--r0:46.0deg;--x1:-16.4846px;--y1:-6.7375px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18151 10.2903L5.15086 9.91483C4.92602 7.39807 2.91268 5.39886 0.378137 5.1756L0 5.14515L0.378137 5.11471C2.91268 4.89145 4.92602 2.89225 5.15086 0.375487L5.18151 0L5.21217 0.375487C5.43701 2.89225 7.45034 4.89145 9.98489 5.11471L10.363 5.14515L9.98489 5.1756C7.45034 5.39886 5.43701 7.39807 5.21217 9.91483L5.18151 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:67.4%;top:31.51%;width:3.75%;height:3.88%;--x0:-47.219px;--y0:41.7751px;--r0:-46.0deg;--x1:10.3882px;--y1:-9.1905px;--r1:11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18151 10.2903L5.15085 9.91482C4.92601 7.39806 2.91268 5.39886 0.378133 5.1756L0 5.14515L0.378133 5.11471C2.91268 4.89145 4.92601 2.89225 5.15085 0.375487L5.18151 0L5.21217 0.375487C5.437 2.89225 7.45033 4.89145 9.98488 5.11471L10.363 5.14515L9.98488 5.1756C7.45033 5.39886 5.437 7.39806 5.21217 9.91482L5.18151 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:63.46%;top:71.24%;width:3.75%;height:3.89%;--x0:-36.3443px;--y0:-64.2541px;--r0:-46.0deg;--x1:7.9957px;--y1:14.1359px;--r1:11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18151 10.2903L5.15085 9.91482C4.92601 7.39806 2.91268 5.39886 0.378133 5.1756L0 5.14515L0.378133 5.11471C2.91268 4.89145 4.92601 2.89225 5.15085 0.375487L5.18151 0L5.21217 0.375487C5.437 2.89225 7.45033 4.89145 9.98488 5.11471L10.363 5.14515L9.98488 5.1756C7.45033 5.39886 5.437 7.39806 5.21217 9.91482L5.18151 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:72.73%;top:39.83%;width:3.76%;height:3.88%;--x0:-61.9455px;--y0:19.5786px;--r0:-46.0deg;--x1:13.628px;--y1:-4.3073px;--r1:11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18152 10.2903L5.15086 9.91482C4.92602 7.39806 2.9127 5.39886 0.378149 5.1756L0 5.14515L0.378149 5.1147C2.9127 4.89144 4.92602 2.89224 5.15086 0.37548L5.18152 0L5.21218 0.37548C5.43702 2.89224 7.45035 4.89144 9.9849 5.1147L10.363 5.14515L9.9849 5.1756C7.45035 5.39886 5.43702 7.39806 5.21218 9.91482L5.18152 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:43.4%;top:18.31%;width:5.63%;height:5.82%;--x0:16.4301px;--y0:74.4203px;--r0:46.0deg;--x1:-3.6146px;--y1:-16.3725px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="15.5343" height="15.4253" viewBox="0 0 15.5343 15.4253" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.76716 15.4253L6.84736 12.2185C6.34659 10.4831 4.97711 9.12326 3.2295 8.626L0 7.71266L3.2295 6.79932C4.97711 6.30205 6.34659 4.94219 6.84736 3.20684L7.76716 0L8.68696 3.20684C9.18774 4.94219 10.5572 6.30205 12.3048 6.79932L15.5343 7.71266L12.3048 8.626C10.5572 9.12326 9.18774 10.4831 8.68696 12.2185L7.76716 15.4253Z" fill="white"/></svg></span>','<span class="__crossx-wc-part" style="left:53.45%;top:13.67%;width:8.11%;height:9.28%;--x0:-14.7411px;--y0:82.1862px;--r0:-46.0deg;--x1:3.243px;--y1:-18.081px;--r1:11.0deg"><svg preserveAspectRatio="none" width="22.3793" height="24.5926" viewBox="0 0 22.3793 24.5926" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M16.7845 3.51007C21.1906 5.1057 23.1825 10.7014 21.235 16.0178C19.2875 21.3341 14.1335 24.3488 9.72748 22.7606L6.51367 21.3561L14.2816 2.52475L16.7845 3.51007Z" fill="#6D45D2"/><path d="M19.2947 14.8182C20.9983 9.42011 18.7506 3.91485 14.2744 2.52192C9.79811 1.12899 4.78832 4.37586 3.08469 9.774C1.38106 15.1721 3.62872 20.6774 8.10498 22.0703C12.5812 23.4632 17.591 20.2164 19.2947 14.8182Z" fill="#A872FF"/><path d="M12.9006 3.73181C13.3301 3.8127 13.7374 3.94505 14.1298 4.12153C13.9595 4.07006 13.7744 4.02594 13.5967 3.98917C9.82747 3.25386 6.00643 6.50394 5.07339 11.2173C4.53282 13.9453 5.08079 16.7321 6.53219 18.6881C7.21346 19.6072 8.05024 20.2984 8.99069 20.7249C7.76144 20.3572 6.6803 19.5705 5.84352 18.4307C4.39212 16.4674 3.85155 13.6732 4.38472 10.9526C5.31776 6.23188 9.14619 2.98915 12.908 3.72446L12.9006 3.73181Z" fill="#6D45D2"/><path d="M11.7916 6.49461L8.41779 8.51979C7.82275 8.87508 7.59466 9.70708 7.90998 10.3664C8.2253 11.0257 8.97184 11.2735 9.56688 10.9182L12.4206 9.2046L11.039 10.7534L10.8461 16.9886C10.8229 17.7398 11.3553 18.3699 12.0306 18.3905C12.706 18.4111 13.2763 17.8147 13.2996 17.0634L13.5883 7.73112C13.5963 7.47047 13.5307 7.21269 13.4441 7.04123C13.1194 6.38676 12.3822 6.13407 11.7872 6.48936L11.7916 6.49461Z" fill="white"/></g></svg></span>','<span class="__crossx-wc-part __crossx-wc-part--rotated" style="left:76.25%;top:55.32%;width:16.5%;height:17.24%;--x0:-103.5548px;--y0:-33.6647px;--r0:-46.0deg;--x1:22.782px;--y1:7.4062px;--r1:11.0deg"><svg style="transform:matrix(0.77594,0.63081,-0.63611,0.77160,0,0)" preserveAspectRatio="none" width="30.7832" height="34.053" viewBox="0 0 30.7832 34.053" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M23.0894 4.85667C29.1483 7.06598 31.8871 14.815 29.2084 22.1775C26.5297 29.54 19.4419 33.7155 13.383 31.5164L8.9636 29.5717L19.6476 3.49238L23.0894 4.85667Z" fill="#F21C69"/><path d="M26.5372 20.5162C28.8822 13.04 25.7931 5.41697 19.6376 3.48967C13.4821 1.56238 6.59101 6.06065 4.24601 13.5368C1.901 21.013 4.99004 28.636 11.1456 30.5633C17.3011 32.4906 24.1922 27.9924 26.5372 20.5162Z" fill="url(#__cx-wc-7d32a-paint0_linear_0_47)"/><path d="M17.7415 5.16219C18.3321 5.27416 18.8921 5.4574 19.4317 5.70174C19.1976 5.63048 18.943 5.5694 18.6986 5.51851C13.5159 4.50062 8.26144 9.00146 6.97804 15.5283C6.23449 19.3059 6.98775 23.1649 8.98332 25.8732C9.92002 27.1459 11.0706 28.103 12.3637 28.6935C10.6735 28.1845 9.1869 27.0951 8.03639 25.5169C6.04081 22.7984 5.29774 18.9292 6.03111 15.1618C7.31451 8.62478 12.5791 4.13412 17.7517 5.15201L17.7415 5.16219Z" fill="#F21C69"/><path d="M16.2181 8.98864L11.5789 11.7932C10.7607 12.2852 10.447 13.4372 10.8805 14.3501C11.314 15.263 12.3404 15.6061 13.1586 15.1141L17.0826 12.7409L15.1828 14.8857L14.9169 23.5191C14.8848 24.5594 15.6167 25.4318 16.5454 25.4603C17.474 25.4887 18.2582 24.6627 18.2903 23.6225L18.6883 10.7006C18.6994 10.3396 18.6092 9.98272 18.4901 9.74532C18.0438 8.83915 17.0302 8.48935 16.212 8.98137L16.2181 8.98864Z" fill="white"/></g><defs><linearGradient id="__cx-wc-7d32a-paint0_linear_0_47" x1="10.0062" y1="30.4051" x2="22.1393" y2="4.29565" gradientUnits="userSpaceOnUse"><stop stop-color="#FF85B2"/><stop offset="0.3" stop-color="#FF75A1"/><stop offset="0.69" stop-color="#FF6892"/><stop offset="1" stop-color="#FF648D"/></linearGradient></defs></svg></span>','<span class="__crossx-wc-part" style="left:9.15%;top:27.18%;width:10.41%;height:10.87%;--x0:104.3547px;--y0:44.0181px;--r0:46.0deg;--x1:-22.958px;--y1:-9.684px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="28.7144" height="28.8038" viewBox="0 0 28.7144 28.8038" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M5.69433 2.84346C-0.253684 5.91837 -1.78668 13.9558 2.26042 20.7957C6.31774 27.6356 14.4222 30.6801 20.3702 27.6051L24.6421 25.0275L9.05669 0.986328L5.69433 2.84346Z" fill="url(#__cx-wc-fc6d3-paint0_linear_0_27)"/><path d="M26.8181 8.56904C23.0981 1.56676 15.1469 -1.82275 9.05586 0.988314C2.96477 3.79937 1.04342 11.7657 4.76348 18.768C8.48354 25.7703 16.4347 29.1598 22.5258 26.3487C28.6168 23.5377 30.5382 15.5713 26.8181 8.56904Z" fill="url(#__cx-wc-fc6d3-paint1_linear_0_27)"/><path d="M21.5361 24.4592C20.974 24.7231 20.3812 24.9159 19.7783 25.0377C20.0235 24.9565 20.2688 24.8448 20.5141 24.7434C25.5014 22.4397 26.9833 15.7216 23.8254 9.76456C21.996 6.32431 18.8687 3.71621 15.445 2.76228C13.8405 2.31575 12.2564 2.24472 10.7949 2.55932C12.5425 1.95042 14.4843 1.91997 16.467 2.47813C19.8907 3.43206 23.018 6.05031 24.8576 9.48041C28.0155 15.4273 26.5336 22.1556 21.5463 24.4592H21.5361Z" fill="#F21C69"/><path d="M14.2883 5.68047L9.9279 9.22654C9.15843 9.84935 9.01876 11.0458 9.61565 11.8823C10.2125 12.7188 11.3327 12.8921 12.1022 12.2693L15.7902 9.26895L14.1652 11.7114L15.2815 20.3365C15.416 21.3758 16.316 22.1234 17.284 21.9998C18.2519 21.8763 18.9323 20.9271 18.7978 19.8878L17.127 6.97832C17.0803 6.61775 16.9292 6.27771 16.7673 6.06121C16.1582 5.23343 15.0503 5.05142 14.2808 5.67424L14.2883 5.68047Z" fill="white"/></g><defs><linearGradient id="__cx-wc-fc6d3-paint0_linear_0_27" x1="-0.164129" y1="13.6703" x2="25.534" y2="16.3173" gradientUnits="userSpaceOnUse"><stop stop-color="#FF4A8D"/><stop offset="0.1" stop-color="#FB4489"/><stop offset="0.23" stop-color="#F1357F"/><stop offset="0.36" stop-color="#E11D6F"/><stop offset="0.4" stop-color="#DB1469"/><stop offset="0.74" stop-color="#DB1569"/><stop offset="0.86" stop-color="#DB1C69"/><stop offset="0.95" stop-color="#DB2869"/><stop offset="1" stop-color="#DB3569"/></linearGradient><linearGradient id="__cx-wc-fc6d3-paint1_linear_0_27" x1="2.69461" y1="12.3407" x2="28.8706" y2="15.037" gradientUnits="userSpaceOnUse"><stop stop-color="#FF85B2"/><stop offset="0.3" stop-color="#FF75A1"/><stop offset="0.69" stop-color="#FF6892"/><stop offset="1" stop-color="#FF648D"/></linearGradient></defs></svg></span>','<span class="__crossx-wc-part" style="left:75.64%;top:27.76%;width:8.3%;height:10.48%;--x0:-76.2471px;--y0:42.9853px;--r0:-46.0deg;--x1:16.7744px;--y1:-9.4568px;--r1:11.0deg"><svg preserveAspectRatio="none" width="22.8957" height="27.775" viewBox="0 0 22.8957 27.775" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M14.2637 27.5528C12.1073 28.7908 7.40613 24.7315 3.76783 18.4904C0.119304 12.2391 -1.08665 6.18058 1.06976 4.93235L5.70963 2.24306L18.9036 24.8635L14.2637 27.5528Z" fill="#6D45D2"/><path d="M19.026 24.74C21.1632 23.4729 19.8745 17.4211 16.1477 11.223C12.4208 5.02483 7.66706 1.02742 5.52988 2.2945C3.39269 3.56159 4.68137 9.61335 8.40822 15.8115C12.1351 22.0096 16.8888 26.007 19.026 24.74Z" fill="#A872FF"/><path d="M15.1838 11.7804C18.4951 17.2706 19.8748 22.5173 18.26 23.461C18.0965 23.5625 17.9126 23.6031 17.7184 23.6031C17.7695 23.593 17.8206 23.5727 17.8615 23.5422C19.466 22.5984 18.0863 17.362 14.7852 11.8616C11.8112 6.90928 8.28536 3.42843 6.43555 3.48932C8.12184 2.78909 11.9748 6.43231 15.1838 11.7804Z" fill="#6D45D2"/><path d="M8.50038 6.8516L7.92883 10.3329C7.82678 10.9448 8.24482 11.9586 8.85575 12.5835C9.46668 13.2085 10.0504 13.2176 10.1525 12.6057L10.6355 9.6603L10.8741 11.8917L14.8619 18.9437C15.3424 19.7935 16.0565 20.3077 16.4508 20.0878C16.8451 19.868 16.7747 18.9949 16.2942 18.1452L10.3257 7.59022C10.159 7.29542 9.95265 7.03032 9.79113 6.86948C9.17811 6.2533 8.59648 6.23544 8.49443 6.84732L8.50038 6.8516Z" fill="white"/></g></svg></span>','<span class="__crossx-wc-part __crossx-wc-part--rotated" style="left:19.56%;top:63.74%;width:9%;height:10.13%;--x0:81.0429px;--y0:-56.7374px;--r0:46.0deg;--x1:-17.8294px;--y1:12.4822px;--r1:-11.0deg"><svg style="transform:matrix(0.92726,-0.37441,0.37920,0.92531,0,0)" preserveAspectRatio="none" width="17.8794" height="21.7754" viewBox="0 0 17.8794 21.7754" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M11.1385 21.5985C9.45751 22.5682 5.78879 19.3821 2.94775 14.4856C0.0987301 9.58109 -0.845253 4.82918 0.835783 3.8515L4.45281 1.74512L14.7556 19.4921L11.1385 21.5985Z" fill="#6D45D2"/><path d="M14.8635 19.3867C16.5291 18.3968 15.5168 13.6557 12.6025 8.79715C9.68823 3.9386 5.97547 0.802455 4.30984 1.79238C2.64422 2.7823 3.65647 7.52343 6.57077 12.382C9.48508 17.2405 13.1979 20.3767 14.8635 19.3867Z" fill="#A872FF"/><path d="M11.8531 9.22923C14.4381 13.5359 15.5168 17.6505 14.2582 18.3897C14.1308 18.4692 13.9874 18.5009 13.836 18.5008C13.8758 18.4929 13.9157 18.477 13.9475 18.4531C15.1981 17.714 14.1194 13.6073 11.5424 9.29267C9.22073 5.40791 6.46956 2.67665 5.02725 2.72338C6.34171 2.17526 9.34796 5.03401 11.8531 9.22923Z" fill="#6D45D2"/><path d="M6.63149 5.36631L6.18974 8.09188C6.11085 8.57093 6.43802 9.36528 6.91517 9.85536C7.39233 10.3454 7.84757 10.3532 7.92645 9.87417L8.29976 7.5682L8.48844 9.31584L11.6064 14.8428C11.9821 15.5087 12.5396 15.9122 12.8468 15.7405C13.1541 15.5688 13.0982 14.885 12.7225 14.2191L8.05583 5.94677C7.92549 5.71573 7.76427 5.5079 7.63813 5.38176C7.15934 4.89855 6.70573 4.8839 6.62685 5.36295L6.63149 5.36631Z" fill="white"/></g></svg></span>','<span class="__crossx-wc-wallet"><svg style="transform:matrix(0.97379,0.22745,-0.22745,0.97379,0,0)" width="88.42" height="88.42" viewBox="0 0 88.42 88.42" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="__cx-wc-wallet-clip"><path d="M44.2101 1.58818e-05C9.30971 1.58818e-05 0 9.30973 0 44.2101C0 79.1105 9.30971 88.4202 44.2101 88.4202C79.1105 88.4202 88.4202 79.1105 88.4202 44.2101C88.4202 9.30973 79.1105 1.58818e-05 44.2101 1.58818e-05Z"/></clipPath><clipPath id="__cx-wc-wallet-clip2"><path transform="translate(0.1 0.01)" d="M44.2101 1.58818e-05C9.30971 1.58818e-05 0 9.30973 0 44.2101C0 79.1105 9.30971 88.4202 44.2101 88.4202C79.1105 88.4202 88.4202 79.1105 88.4202 44.2101C88.4202 9.30973 79.1105 1.58818e-05 44.2101 1.58818e-05Z"/></clipPath></defs><g clip-path="url(#__cx-wc-wallet-clip)"><svg x="0.000" y="0.044" width="88.393" height="88.376" viewBox="0 0 88.3978 88.3761" preserveAspectRatio="none" overflow="visible"><g><path d="M88.3761 0L0 0L0 88.3761H88.3761V0Z" fill="url(#__cx-wc-ab720-paint0_linear_0_228)"/><g><path d="M30.885 88.3759H88.3978V16.8103L30.885 53.652L30.885 88.3759Z" fill="url(#__cx-wc-ab720-paint1_linear_0_228)"/><path d="M30.8867 88.3754H0.00143051L0.00143051 21.0013L30.8867 53.6515L30.8867 88.3754Z" fill="url(#__cx-wc-ab720-paint2_linear_0_228)"/></g></g><defs><linearGradient id="__cx-wc-ab720-paint0_linear_0_228" x1="-10.2363" y1="-10.6554" x2="94.2222" y2="94.5531" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="__cx-wc-ab720-paint1_linear_0_228" x1="22.0606" y1="20.2959" x2="65.1015" y2="57.2921" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="__cx-wc-ab720-paint2_linear_0_228" x1="55.1317" y1="3.02165" x2="14.4513" y2="55.9899" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient></defs></svg></g><g clip-path="url(#__cx-wc-wallet-clip2)"><rect y="0.44" width="88.42" height="88.42" fill="#fff"/><svg x="-2.750" y="0.413" width="93.929" height="93.140" viewBox="0 0 93.9211 93.1421" preserveAspectRatio="none" overflow="visible"><g><path d="M91.1837 0H2.76347L2.76347 88.4202H91.1837V0Z" fill="#CE3E35"/><path d="M13.5066 17.7839C13.5066 13.7731 16.758 10.5216 20.7689 10.5216H73.1521C77.163 10.5216 80.4144 13.7731 80.4144 17.7839V47.0786H13.5066L13.5066 17.7839Z" fill="white"/><g filter="url(#__cx-wc-050c7-filter0_d_0_83)"><path d="M91.158 91.0698H2.76313L2.76313 24.5964C2.76313 21.5443 5.23732 19.0701 8.28939 19.0701H32.9437C35.5525 19.0701 37.6858 21.0278 39.2584 23.1092C41.0469 25.4762 43.8319 26.9978 46.9604 26.9978C50.0889 26.9978 52.874 25.4762 54.6625 23.1092C56.2352 21.0278 58.3685 19.0701 60.9772 19.0701H85.6317C88.6838 19.0701 91.158 21.5443 91.158 24.5964V91.0698Z" fill="url(#__cx-wc-050c7-paint0_linear_0_83)"/></g><g><path d="M33.643 91.0285H91.1559V27.7523L33.643 64.594V91.0285Z" fill="url(#__cx-wc-050c7-paint1_linear_0_83)"/><path d="M33.6463 91.0735H2.76103L2.76103 32.0876L33.6463 64.7378V91.0735Z" fill="url(#__cx-wc-050c7-paint2_linear_0_83)"/></g></g><defs><filter id="__cx-wc-050c7-filter0_d_0_83" x="8.9407e-08" y="15.6162" width="93.9211" height="77.5259" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dy="-0.690783"/><feGaussianBlur stdDeviation="1.38157"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.892803 0 0 0 0 0.220099 0 0 0 0 0.293135 0 0 0 0.5 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_0_83"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_0_83" result="shape"/></filter><linearGradient id="__cx-wc-050c7-paint0_linear_0_83" x1="-7.47531" y1="10.2228" x2="77.666" y2="113.52" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="__cx-wc-050c7-paint1_linear_0_83" x1="24.8187" y1="31.2379" x2="67.8595" y2="68.2341" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="__cx-wc-050c7-paint2_linear_0_83" x1="57.8913" y1="14.108" x2="17.211" y2="67.0762" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient></defs></svg><svg x="26.299" y="32.289" width="29.201" height="48.231" viewBox="0 0 29.1992 48.2295" preserveAspectRatio="none" overflow="visible"><g filter="url(#__cx-wc-2c959-filter0_d_0_4)"><path d="M17.5095 3.62052L5.20252 10.7339C3.03172 11.9822 2.27963 14.7865 3.52741 16.9582C4.7752 19.1298 7.57844 19.8822 9.74925 18.6339L20.1589 12.6149L15.2019 17.9328L15.2019 38.7943C15.2019 41.3079 17.2531 43.3598 19.7657 43.3598C22.2784 43.3598 24.3295 41.3079 24.3295 38.7943V7.57051C24.3295 6.69844 24.0561 5.84346 23.7142 5.27917C22.4322 3.12463 19.6632 2.35515 17.4924 3.60342L17.5095 3.62052Z" fill="white"/><g></g></g><defs><filter id="__cx-wc-2c959-filter0_d_0_4" x="-4.91855e-08" y="0.0794639" width="29.1992" height="48.15" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="0.972558" dy="0.972558"/><feGaussianBlur stdDeviation="1.94855"/><feColorMatrix type="matrix" values="0 0 0 0 0.831373 0 0 0 0 0.113725 0 0 0 0 0.356863 0 0 0 0.3 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_0_4"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_0_4" result="shape"/></filter></defs></svg></g></svg></span>'].join(""),vc=`
8
+ .__crossx-wallet-created-illust {
9
+ display: block;
10
+ position: relative;
11
+ width: 276px;
12
+ height: 265px;
13
+ flex: none;
14
+ }
15
+ .__crossx-wc-part,
16
+ .__crossx-wc-wallet {
17
+ position: absolute;
18
+ display: block;
19
+ transform-origin: 50% 50%;
20
+ }
21
+ .__crossx-wc-part > svg,
22
+ .__crossx-wc-wallet > svg {
23
+ display: block;
24
+ flex: none;
25
+ }
26
+ .__crossx-wc-part--rotated,
27
+ .__crossx-wc-wallet {
28
+ display: flex;
29
+ align-items: center;
30
+ justify-content: center;
31
+ }
32
+ .__crossx-wc-part {
33
+ animation: __crossx-wc-burst 2s linear both;
34
+ }
35
+ /* 별·파티클(흰 단색 조각)만 테마 색을 따른다 — 코인·지갑의 흰 '1' 은 그대로 흰색 */
36
+ .__crossx-wc-sparkle path {
37
+ fill: var(--cx-wc-sparkle, #FFFFFF);
38
+ }
39
+ .__crossx-wc-wallet {
40
+ left: 79.65px;
41
+ top: 86.91px;
42
+ width: 106.214px;
43
+ height: 106.214px;
44
+ animation:
45
+ __crossx-wc-wallet-rise 2s linear both,
46
+ __crossx-wc-wallet-tilt 2s linear both,
47
+ __crossx-wc-wallet-fade 2s linear both;
48
+ }
49
+ /* 코인·반짝이: 지갑 중심에서 튀어나와(1.28배) 스프링으로 제자리 */
50
+ @keyframes __crossx-wc-burst {
51
+ 0%, 13.5% {
52
+ translate: var(--x0) var(--y0);
53
+ rotate: var(--r0);
54
+ scale: 0.045;
55
+ animation-timing-function: cubic-bezier(0.08, 0.82, 0.18, 1);
56
+ }
57
+ 23.5% {
58
+ translate: var(--x1) var(--y1);
59
+ rotate: var(--r1);
60
+ scale: 1.28;
61
+ animation-timing-function: ${yr};
62
+ }
63
+ 37.5%, 100% {
64
+ translate: 0px 0px;
65
+ rotate: 0deg;
66
+ scale: 1;
67
+ }
68
+ }
69
+ /* 지갑: 아래에서 솟아오르며 살짝 눌렸다 복원 */
70
+ @keyframes __crossx-wc-wallet-rise {
71
+ 0%, 0.053% {
72
+ translate: 0px 104px;
73
+ scale: 0.9 0.9;
74
+ animation-timing-function: cubic-bezier(0.14, 0.74, 0.24, 1);
75
+ }
76
+ 27.247% {
77
+ translate: 0px -5px;
78
+ scale: 1.035 0.975;
79
+ animation-timing-function: ${yr};
80
+ }
81
+ 37.445%, 100% {
82
+ translate: 0px 0px;
83
+ scale: 1 1;
84
+ }
85
+ }
86
+ /* 지갑: 좌우로 흔들리다 정지 */
87
+ @keyframes __crossx-wc-wallet-tilt {
88
+ 0%, 0.053% { rotate: -11.0deg; animation-timing-function: ease-in-out; }
89
+ 9.118% { rotate: 8.0deg; animation-timing-function: ease-in-out; }
90
+ 17.616% { rotate: -5.0deg; animation-timing-function: ease-in-out; }
91
+ 26.114% { rotate: 2.5deg; animation-timing-function: ${yr}; }
92
+ 36.312%, 100% { rotate: 0deg; }
93
+ }
94
+ @keyframes __crossx-wc-wallet-fade {
95
+ 0% { opacity: 0; animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1); }
96
+ 8%, 100% { opacity: 1; }
97
+ }
98
+ @media (prefers-reduced-motion: reduce) {
99
+ .__crossx-wc-part,
100
+ .__crossx-wc-wallet {
101
+ animation: none;
102
+ }
103
+ }
104
+ `,vn="__crossx-confirm-style",Y="__crossx-confirm-overlay",Ec={light:{bg:"#FFFFFF",border:"rgba(0,0,0,0.07)",borderMedium:"rgba(0,0,0,0.18)",titleColor:"#000000",contentHigh:"rgba(0,0,0,0.85)",subtitleColor:"rgba(0,0,0,0.65)",labelColor:"rgba(0,0,0,0.65)",valueColor:"#000000",pillBg:"#F5F7FA",pillFromColor:"rgba(0,0,0,0.65)",pillAmtColor:"#000000",divider:"rgba(0,0,0,0.07)",closeColor:"rgba(0,0,0,0.40)",closeHoverBg:"#F5F7FA",copyColor:"rgba(0,0,0,0.65)",inputBg:"#F5F7FA",inputBorder:"rgba(0,0,0,0.07)",hintColor:"rgba(0,0,0,0.45)",surfaceSubtle:"#F5F7FA",surfaceHigh:"#EDF1F2",primary:"#7E54F4",primaryGlow:"rgba(126,84,244,0.20)",primaryGradient:"#7E54F4",secondary:"#D20609",errorColor:"#D20609",noticeBg:"#FFF6F6",noticeBorder:"#DA0B2E",noticeTitleColor:"#D20609",onPrimary:"#FFFFFF",sparkleColor:"#FFAA1F",warningColor:"#E56F00"},dark:{bg:"#1E232E",border:"rgba(255,255,255,0.07)",borderMedium:"rgba(255,255,255,0.18)",titleColor:"#FFFFFF",contentHigh:"rgba(255,255,255,0.85)",subtitleColor:"rgba(255,255,255,0.65)",labelColor:"rgba(255,255,255,0.65)",valueColor:"#FFFFFF",pillBg:"#252B39",pillFromColor:"rgba(255,255,255,0.65)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.07)",closeColor:"rgba(255,255,255,0.40)",closeHoverBg:"#252B39",copyColor:"rgba(255,255,255,0.65)",inputBg:"#252B39",inputBorder:"rgba(255,255,255,0.07)",hintColor:"rgba(255,255,255,0.45)",surfaceSubtle:"#252B39",surfaceHigh:"#363B4C",primary:"#A392FF",primaryGlow:"rgba(163,146,255,0.20)",primaryGradient:"#A392FF",secondary:"#FF0F47",errorColor:"#EA1546",noticeBg:"#39151E",noticeBorder:"#CD0C40",noticeTitleColor:"#EA1546",onPrimary:"#000000",sparkleColor:"#FFFFFF",warningColor:"#FF9F21"}};function Ic(s,e){const r=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(s.trim());if(!r)return;const t=r[1].length===3?r[1].split("").map(i=>i+i).join(""):r[1],n=parseInt(t,16);return`rgba(${n>>16&255},${n>>8&255},${n&255},${e})`}function En(s,e){const r=Ec[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary,primaryGradient:t.primary,primaryGlow:Ic(t.primary,.2)??r.primaryGlow},...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,contentHigh: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 Ac=`
8
105
  @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
106
 
10
- #${re} {
107
+ #${Y} {
11
108
  position: fixed;
12
109
  inset: 0;
13
110
  z-index: 2147483647;
@@ -16,6 +113,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
16
113
  justify-content: center;
17
114
  background: rgba(0,0,0,0.55);
18
115
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
116
+ /* Figma 렌더와 같은 굵기로 보이도록 서브픽셀 대신 그레이스케일 안티앨리어싱(macOS) — 하위 요소에 상속 */
117
+ -webkit-font-smoothing: antialiased;
118
+ -moz-osx-font-smoothing: grayscale;
119
+ text-rendering: optimizeLegibility;
19
120
  animation: __crossx-fade-in 0.15s ease;
20
121
  pointer-events: auto;
21
122
  }
@@ -24,6 +125,63 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
24
125
  to { opacity: 1; }
25
126
  }
26
127
 
128
+ /* ── 버튼 호버·프레스 공통 ─────────────────────────────────────────
129
+ 호스트 페이지의 전역 \`button:hover\` (떠오름 + 글로우 그림자)가 SDK 버튼에 새지 않게 막고,
130
+ 모든 버튼의 피드백은 배경·보더가 밝아지는 방식으로 통일한다. (넘패드 하단선 그림자는 !important 라 유지) */
131
+ #${Y} button:is(:hover, :focus, :active) {
132
+ box-shadow: none;
133
+ transform: none;
134
+ }
135
+ /* 채움형 CTA — 호버 시 한 단계 밝게, 누르면 살짝 어둡게.
136
+ color-mix 를 모르는 브라우저(Chrome·WebView 111 미만, Safari 16.2 미만)에서는 값이 무효가 돼
137
+ 배경이 투명해지므로 @supports 로 감싼다. 미지원 환경은 기본 배경 그대로 두고 눌림만 남긴다. */
138
+ @supports (color: color-mix(in srgb, red, blue)) {
139
+ #${Y} :is(.__crossx-approve-btn, .__crossx-confirm-btn, .__crossx-wallet-created-btn, .__crossx-pw-btn, .__crossx-pin6-next):not(:disabled):not(.--disabled):not([aria-disabled="true"]):hover {
140
+ background: color-mix(in srgb, var(--cx-primary-gradient) 86%, #FFFFFF) !important;
141
+ }
142
+ #${Y} :is(.__crossx-approve-btn, .__crossx-confirm-btn, .__crossx-wallet-created-btn, .__crossx-pw-btn, .__crossx-pin6-next):not(:disabled):not(.--disabled):not([aria-disabled="true"]):active {
143
+ background: color-mix(in srgb, var(--cx-primary-gradient) 90%, #000000) !important;
144
+ }
145
+ }
146
+ /* 보조(취소) — 호버·프레스 시 한 단계 밝은 표면 */
147
+ #${Y} .__crossx-cancel-btn:not(:disabled):is(:hover, :active) {
148
+ background: var(--cx-surface-high) !important;
149
+ }
150
+ /* 표면형 — 호버 시 한 단계 밝은 표면 */
151
+ #${Y} :is(.__crossx-recover-btn, .__crossx-connect-other-block):not(:disabled):hover {
152
+ background: var(--cx-surface-high) !important;
153
+ }
154
+ /* 지갑 추가(점선) — 표면 + 점선 보더가 밝아진다 */
155
+ #${Y} .__crossx-wallet-add:not(:disabled):hover {
156
+ background: var(--cx-pill-bg);
157
+ border-color: var(--cx-subtitle);
158
+ }
159
+ /* 기존 눌림 스케일은 유지 (공통 reset 보다 우선) */
160
+ #${Y} .__crossx-close:active {
161
+ transform: scale(0.92);
162
+ }
163
+ #${Y} .__crossx-wallet-item:active {
164
+ transform: scale(0.985);
165
+ }
166
+ #${Y} .__crossx-wallet-add:not(:disabled):active {
167
+ transform: scale(0.99);
168
+ }
169
+
170
+ /* 비활성 버튼은 호버·포커스·프레스 효과 없음 — SDK 자체 효과뿐 아니라 호스트 페이지의
171
+ 전역 \`button:hover\` (떠오름·그림자 등)도 막는다. SDK 는 비활성을 \`.--disabled\` 클래스로도
172
+ 표시하므로 \`:disabled\` 만으로는 호스트 규칙을 피할 수 없다. 커서는 모두 not-allowed. */
173
+ #${Y} button:is(:disabled, .--disabled, [aria-disabled="true"]) {
174
+ cursor: not-allowed !important;
175
+ }
176
+ #${Y} button:is(:disabled, .--disabled, [aria-disabled="true"]):is(:hover, :focus, :active) {
177
+ transform: none !important;
178
+ filter: none !important;
179
+ }
180
+ /* 넘패드 키는 하단선을 box-shadow 로 그리므로 그림자 제거에서 뺀다 */
181
+ #${Y} button:is(:disabled, .--disabled, [aria-disabled="true"]):not(.__crossx-pin6-numpad-key):is(:hover, :focus, :active) {
182
+ box-shadow: none !important;
183
+ }
184
+
27
185
  .__crossx-card {
28
186
  background: var(--cx-bg);
29
187
  border: 1px solid var(--cx-border-medium);
@@ -120,32 +278,34 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
120
278
  .__crossx-rows {
121
279
  display: flex;
122
280
  flex-direction: column;
123
- gap: 4px;
281
+ gap: 12px; /* Figma 행 간격 12 */
124
282
  }
125
283
  .__crossx-row {
126
284
  display: flex;
127
285
  align-items: center;
128
- height: 20px;
286
+ min-height: 21px;
129
287
  }
130
288
  .__crossx-row-label {
131
- font-size: 13px;
132
- font-weight: 400;
133
- line-height: 1.3;
134
- color: var(--cx-label);
289
+ font-size: 14px;
290
+ font-weight: 500;
291
+ line-height: 1.5;
292
+ letter-spacing: -0.01em;
293
+ color: var(--cx-close); /* Figma content/low */
135
294
  width: 100px;
136
295
  flex-shrink: 0;
137
296
  }
138
297
  .__crossx-row-value {
139
- font-size: 13px;
140
- font-weight: 400;
141
- line-height: 1.3;
142
- color: var(--cx-value);
298
+ font-size: 14px;
299
+ font-weight: 500;
300
+ line-height: 1.5;
301
+ letter-spacing: -0.01em;
302
+ color: var(--cx-subtitle); /* Figma content/medium */
143
303
  flex: 1;
144
304
  text-align: right;
145
305
  display: flex;
146
306
  align-items: center;
147
307
  justify-content: flex-end;
148
- gap: 4px;
308
+ gap: 6px;
149
309
  min-width: 0;
150
310
  overflow: hidden;
151
311
  }
@@ -194,10 +354,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
194
354
  gap: 8px;
195
355
  }
196
356
  .__crossx-pill-from {
197
- font-size: 16px;
357
+ font-size: 14px;
198
358
  font-weight: 600;
199
- line-height: 1.3;
200
- color: var(--cx-pill-from);
359
+ line-height: 1.5;
360
+ letter-spacing: -0.01em;
361
+ color: var(--cx-close); /* Figma content/low */
201
362
  white-space: nowrap;
202
363
  overflow: hidden;
203
364
  text-overflow: ellipsis;
@@ -205,10 +366,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
205
366
  min-width: 0;
206
367
  }
207
368
  .__crossx-pill-amount {
208
- font-size: 16px;
369
+ font-size: 18px;
209
370
  font-weight: 600;
210
- line-height: 1.3;
211
- color: var(--cx-pill-amt);
371
+ line-height: 1.5;
372
+ letter-spacing: -0.01em;
373
+ color: var(--cx-content-high); /* Figma content/high */
212
374
  text-align: right;
213
375
  white-space: nowrap;
214
376
  flex-shrink: 0;
@@ -375,17 +537,14 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
375
537
  }
376
538
  .__crossx-pw-btn {
377
539
  width: 100%;
378
- height: 48px;
379
540
  border: none;
380
541
  border-radius: 12px;
381
- font-size: 16px;
382
- font-weight: 600;
383
542
  font-family: inherit;
384
543
  cursor: pointer;
385
544
  transition: opacity 0.15s;
386
545
  /* disabled 기본값 = 브랜드 그라데이션 50% 투명도 */
387
546
  background: var(--cx-primary-gradient);
388
- color: #ffffff;
547
+ color: var(--cx-on-primary);
389
548
  opacity: 0.5;
390
549
  letter-spacing: -0.01em;
391
550
  }
@@ -421,13 +580,18 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
421
580
  gap: 6px;
422
581
  }
423
582
  .__crossx-pw-notice-icon {
424
- width: 24px;
425
- height: 24px;
583
+ width: 20px;
584
+ height: 20px;
426
585
  flex-shrink: 0;
427
586
  color: var(--cx-notice-title);
428
587
  }
588
+ .__crossx-pw-notice-icon svg {
589
+ display: block;
590
+ width: 100%;
591
+ height: 100%;
592
+ }
429
593
  .__crossx-pw-notice-title {
430
- font-size: 18px;
594
+ font-size: 16px;
431
595
  font-weight: 600;
432
596
  line-height: 1.5;
433
597
  color: var(--cx-notice-title);
@@ -491,6 +655,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
491
655
  width: 11px;
492
656
  height: 9px;
493
657
  }
658
+ /* Figma: 체크 전에는 빈 원 — 체크 표시는 선택됐을 때만 보인다 */
659
+ .__crossx-pw-notice-check:not(.--checked) svg {
660
+ visibility: hidden;
661
+ }
494
662
  .__crossx-pw-notice-item-text {
495
663
  font-size: 14px;
496
664
  font-weight: 400;
@@ -533,7 +701,23 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
533
701
 
534
702
  /* ── Migration Found Modal ─────────────────────────────────────── */
535
703
  .__crossx-card--migration {
536
- width: 560px;
704
+ width: 480px; /* 서명·전송 모달과 같은 폭(Figma 480) */
705
+ }
706
+ /* 세션 만료·업데이트 안내: Figma 4045:14458 — 본문 padding 24, gap 24 (인라인 스타일을 덮는다) */
707
+ .__crossx-card--migration > .__crossx-body:has(> .__crossx-session-hero) {
708
+ padding: 24px !important;
709
+ gap: 24px !important;
710
+ }
711
+ /* Figma 커넥트 모달: 폭 540, 제목-부제목 간격 4 (래퍼 gap 4 만 쓰고 제목 margin 은 뺀다).
712
+ 모바일의 \`.__crossx-card { width: 100% }\` 가 뒤에 선언돼 있어 시트 폭은 그대로다 */
713
+ .__crossx-card--login {
714
+ width: 540px;
715
+ }
716
+ .__crossx-card--login .__crossx-title {
717
+ margin-bottom: 0;
718
+ }
719
+ .__crossx-login-sheet-handle {
720
+ display: none;
537
721
  }
538
722
  .__crossx-subtitle--body {
539
723
  font-size: 16px;
@@ -553,7 +737,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
553
737
  font-size: 14px;
554
738
  font-weight: 600;
555
739
  line-height: 1.4;
556
- color: var(--cx-value);
740
+ color: var(--cx-content-high); /* Figma content/high */
557
741
  margin: 0;
558
742
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
559
743
  }
@@ -572,8 +756,8 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
572
756
  width: 100%;
573
757
  padding: 16px;
574
758
  background: var(--cx-pill-bg);
575
- border: 1px solid var(--cx-pill-bg);
576
- border-radius: 20px;
759
+ border: none;
760
+ border-radius: 12px;
577
761
  cursor: pointer;
578
762
  appearance: none;
579
763
  -webkit-appearance: none;
@@ -606,10 +790,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
606
790
  display: block;
607
791
  }
608
792
  .__crossx-recover-label {
609
- font-size: 18px;
610
- font-weight: 700;
611
- line-height: 1.3;
612
- color: var(--cx-value);
793
+ font-size: 16px;
794
+ font-weight: 600;
795
+ line-height: 1.5;
796
+ color: var(--cx-content-high);
613
797
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
614
798
  }
615
799
  .__crossx-skip-btn {
@@ -624,7 +808,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
624
808
  background: none;
625
809
  border: none;
626
810
  width: 100%;
627
- font-family: 'Sora', -apple-system, sans-serif;
811
+ font-family: inherit;
628
812
  padding: 0;
629
813
  appearance: none;
630
814
  -webkit-appearance: none;
@@ -764,10 +948,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
764
948
 
765
949
  /* ── Signature Request modals (message & typed data) ───────── */
766
950
  .__crossx-sig-subtitle {
767
- font-size: 18px;
951
+ font-size: 16px;
768
952
  font-weight: 600;
769
- line-height: 1.3;
770
- color: var(--cx-title);
953
+ line-height: 1.5;
954
+ letter-spacing: -0.01em;
955
+ color: var(--cx-content-high); /* Figma content/high */
771
956
  text-align: center;
772
957
  margin: 0;
773
958
  }
@@ -785,22 +970,26 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
785
970
  .__crossx-addr-pill-text {
786
971
  font-size: 18px;
787
972
  font-weight: 600;
788
- line-height: 1.3;
789
- color: var(--cx-value);
973
+ line-height: 1.5;
974
+ letter-spacing: -0.01em;
975
+ font-family: 'JetBrains Mono', ui-monospace, monospace; /* Figma 주소 = mono */
976
+ color: var(--cx-content-high);
790
977
  }
791
978
  .__crossx-warning {
792
979
  font-size: 14px;
793
980
  font-weight: 400;
794
- line-height: 1.3;
795
- color: var(--cx-subtitle);
981
+ line-height: 1.5;
982
+ letter-spacing: -0.01em;
983
+ color: var(--cx-warning); /* Figma system/orange/high */
796
984
  text-align: center;
797
985
  margin: 0;
798
986
  }
799
987
  .__crossx-msg-raw {
800
- font-size: 14px;
988
+ font-size: 12px;
801
989
  font-weight: 400;
802
- line-height: 1.3;
803
- color: var(--cx-label);
990
+ line-height: 1.5;
991
+ letter-spacing: -0.01em;
992
+ color: var(--cx-subtitle);
804
993
  white-space: pre-wrap;
805
994
  word-break: break-all;
806
995
  max-height: 200px;
@@ -810,40 +999,43 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
810
999
  .__crossx-td-rows {
811
1000
  display: flex;
812
1001
  flex-direction: column;
813
- gap: 4px;
1002
+ gap: 12px;
814
1003
  }
815
1004
  .__crossx-td-row {
816
1005
  display: flex;
817
1006
  align-items: center;
818
1007
  justify-content: space-between;
819
- min-height: 20px;
1008
+ min-height: 21px;
820
1009
  gap: 20px;
821
1010
  }
822
1011
  .__crossx-td-label {
823
- font-size: 13px;
824
- font-weight: 400;
825
- line-height: 1.3;
826
- color: var(--cx-label);
1012
+ font-size: 14px;
1013
+ font-weight: 500;
1014
+ line-height: 1.5;
1015
+ letter-spacing: -0.01em;
1016
+ color: var(--cx-close); /* Figma content/low */
827
1017
  flex-shrink: 0;
828
1018
  }
829
1019
  .__crossx-td-value {
830
- font-size: 13px;
831
- font-weight: 400;
832
- line-height: 1.3;
833
- color: var(--cx-value);
1020
+ font-size: 14px;
1021
+ font-weight: 500;
1022
+ line-height: 1.5;
1023
+ letter-spacing: -0.01em;
1024
+ color: var(--cx-subtitle); /* Figma content/medium */
834
1025
  text-align: right;
835
1026
  display: flex;
836
1027
  align-items: center;
837
1028
  justify-content: flex-end;
838
- gap: 4px;
1029
+ gap: 6px;
839
1030
  min-width: 0;
840
1031
  }
841
1032
 
842
1033
  /* ── Transaction modals ────────────────────────────────────── */
843
1034
  .__crossx-tx-subtitle {
844
- font-size: 14px;
1035
+ font-size: 16px;
845
1036
  font-weight: 400;
846
- line-height: 1.3;
1037
+ line-height: 1.5;
1038
+ letter-spacing: -0.01em;
847
1039
  color: var(--cx-subtitle);
848
1040
  margin: 0;
849
1041
  }
@@ -851,9 +1043,9 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
851
1043
  background: var(--cx-pill-bg);
852
1044
  border-radius: 12px;
853
1045
  padding: 16px;
854
- font-size: 13px;
1046
+ font-size: 12px;
855
1047
  font-weight: 400;
856
- line-height: 1.6;
1048
+ line-height: 1.5;
857
1049
  color: var(--cx-label);
858
1050
  white-space: pre-wrap;
859
1051
  word-break: break-all;
@@ -865,16 +1057,13 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
865
1057
  }
866
1058
  .__crossx-approve-btn {
867
1059
  width: 100%;
868
- padding: 16px;
869
- border: 1px solid var(--cx-border);
1060
+ border: none;
870
1061
  border-radius: 12px;
871
1062
  background: var(--cx-primary-gradient);
872
- color: #ffffff;
1063
+ color: var(--cx-on-primary);
873
1064
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
874
- font-size: 18px;
875
- font-weight: 700;
876
- line-height: 1.3;
877
1065
  cursor: pointer;
1066
+ height: 48px;
878
1067
  }
879
1068
  .__crossx-approve-btn:hover,
880
1069
  .__crossx-approve-btn:focus,
@@ -885,7 +1074,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
885
1074
  filter: none !important;
886
1075
  transform: none !important;
887
1076
  background: var(--cx-primary-gradient) !important;
888
- color: #ffffff !important;
1077
+ color: var(--cx-on-primary) !important;
889
1078
  }
890
1079
  .__crossx-btn-row {
891
1080
  display: flex;
@@ -894,16 +1083,13 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
894
1083
  }
895
1084
  .__crossx-cancel-btn {
896
1085
  flex: 1;
897
- padding: 16px;
898
- border: 1px solid var(--cx-primary);
1086
+ border: none;
899
1087
  border-radius: 12px;
900
- background: none;
901
- color: var(--cx-primary);
1088
+ background: var(--cx-pill-bg); /* Figma: 보조 버튼 = surface/medium 채움 */
1089
+ color: var(--cx-subtitle);
902
1090
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
903
- font-size: 18px;
904
- font-weight: 700;
905
- line-height: 1.3;
906
1091
  cursor: pointer;
1092
+ height: 48px;
907
1093
  }
908
1094
  .__crossx-cancel-btn:hover,
909
1095
  .__crossx-cancel-btn:focus,
@@ -913,21 +1099,18 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
913
1099
  outline: none !important;
914
1100
  filter: none !important;
915
1101
  transform: none !important;
916
- background: none !important;
917
- color: var(--cx-primary) !important;
1102
+ background: var(--cx-pill-bg) !important;
1103
+ color: var(--cx-subtitle) !important;
918
1104
  }
919
1105
  .__crossx-confirm-btn {
920
1106
  flex: 1;
921
- padding: 16px;
922
- border: 1px solid var(--cx-border);
1107
+ border: none;
923
1108
  border-radius: 12px;
924
1109
  background: var(--cx-primary-gradient);
925
- color: #ffffff;
1110
+ color: var(--cx-on-primary);
926
1111
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
927
- font-size: 18px;
928
- font-weight: 700;
929
- line-height: 1.3;
930
1112
  cursor: pointer;
1113
+ height: 48px;
931
1114
  }
932
1115
  .__crossx-confirm-btn:hover,
933
1116
  .__crossx-confirm-btn:focus,
@@ -938,7 +1121,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
938
1121
  filter: none !important;
939
1122
  transform: none !important;
940
1123
  background: var(--cx-primary-gradient) !important;
941
- color: #ffffff !important;
1124
+ color: var(--cx-on-primary) !important;
942
1125
  }
943
1126
 
944
1127
  /* ── Sign/Send modals: max-height + sticky buttons ─────────── */
@@ -1011,7 +1194,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1011
1194
  .__crossx-progress-text {
1012
1195
  font-size: 14px;
1013
1196
  font-weight: 400;
1014
- line-height: 1.4;
1197
+ line-height: 1.5;
1015
1198
  color: var(--cx-label);
1016
1199
  text-align: center;
1017
1200
  margin: 0;
@@ -1028,9 +1211,8 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1028
1211
  .__crossx-total-label {
1029
1212
  font-size: 14px;
1030
1213
  font-weight: 600;
1031
- line-height: 1.4;
1032
- color: var(--cx-pill-from);
1033
- font-family: 'Sora', 'Pretendard', -apple-system, sans-serif;
1214
+ line-height: 1.5;
1215
+ color: var(--cx-close);
1034
1216
  }
1035
1217
  .__crossx-total-amount {
1036
1218
  font-size: 16px;
@@ -1040,10 +1222,12 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1040
1222
  text-align: right;
1041
1223
  white-space: nowrap;
1042
1224
  flex-shrink: 0;
1043
- font-family: 'Sora', 'Pretendard', -apple-system, sans-serif;
1044
1225
  }
1045
1226
 
1046
1227
  /* ── Login Selector Modal ──────────────────────────────────── */
1228
+ .__crossx-card--login .__crossx-body {
1229
+ padding-top: 24px;
1230
+ }
1047
1231
  .__crossx-login-btn-row {
1048
1232
  display: flex;
1049
1233
  gap: 8px;
@@ -1053,13 +1237,13 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1053
1237
  flex: 1;
1054
1238
  display: flex;
1055
1239
  flex-direction: column;
1056
- gap: 16px;
1240
+ gap: 8px;
1057
1241
  padding: 16px;
1058
1242
  background: var(--cx-pill-bg);
1059
- border: 1px solid var(--cx-border);
1060
- border-radius: 20px;
1243
+ border: none;
1244
+ border-radius: 12px;
1061
1245
  cursor: pointer;
1062
- align-items: flex-start;
1246
+ align-items: center;
1063
1247
  justify-content: center;
1064
1248
  appearance: none;
1065
1249
  -webkit-appearance: none;
@@ -1068,6 +1252,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1068
1252
  outline: none;
1069
1253
  min-width: 0;
1070
1254
  }
1255
+ .__crossx-login-btn {
1256
+ transition: background-color 0.15s ease, transform 0.1s ease;
1257
+ }
1258
+ /* 호스트 CSS 간섭 차단(기존 reset) — 상태별 배경·스케일은 아래에서 다시 지정 */
1071
1259
  .__crossx-login-btn:hover,
1072
1260
  .__crossx-login-btn:focus,
1073
1261
  .__crossx-login-btn:active {
@@ -1078,18 +1266,34 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1078
1266
  transform: none !important;
1079
1267
  background: var(--cx-pill-bg) !important;
1080
1268
  }
1269
+ /* 호버: 한 단계 밝은 표면 (터치 기기는 hover 가 남지 않도록 제외) */
1270
+ @media (hover: hover) {
1271
+ .__crossx-login-btn:hover {
1272
+ background: var(--cx-surface-high) !important;
1273
+ }
1274
+ }
1275
+ /* 프레스: 표면 + 살짝 눌림 */
1276
+ .__crossx-login-btn:active {
1277
+ background: var(--cx-surface-high) !important;
1278
+ transform: scale(0.98) !important;
1279
+ }
1280
+ .__crossx-login-btn:focus-visible {
1281
+ outline: 2px solid var(--cx-primary) !important;
1282
+ outline-offset: 2px;
1283
+ }
1081
1284
  .__crossx-login-btn-label {
1082
- font-size: 18px;
1083
- font-weight: 700;
1084
- line-height: 1.3;
1085
- color: var(--cx-value);
1285
+ font-size: 14px;
1286
+ font-weight: 600;
1287
+ line-height: 1.5;
1288
+ letter-spacing: -0.01em;
1289
+ color: var(--cx-content-high);
1086
1290
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1087
- text-align: left;
1291
+ text-align: center;
1088
1292
  white-space: nowrap;
1089
1293
  }
1090
1294
  .__crossx-login-icon {
1091
- width: 40px;
1092
- height: 40px;
1295
+ width: 32px;
1296
+ height: 32px;
1093
1297
  flex-shrink: 0;
1094
1298
  display: flex;
1095
1299
  align-items: center;
@@ -1098,7 +1302,8 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
1098
1302
  .__crossx-login-terms {
1099
1303
  font-size: 12px;
1100
1304
  font-weight: 400;
1101
- line-height: 1.3;
1305
+ line-height: 1.5;
1306
+ letter-spacing: -0.01em;
1102
1307
  color: var(--cx-subtitle);
1103
1308
  text-align: center;
1104
1309
  font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
@@ -1243,7 +1448,7 @@ button.__crossx-connect-other-block:active {
1243
1448
  flex-direction: column;
1244
1449
  overflow: hidden;
1245
1450
  background: var(--cx-bg);
1246
- border: 1px solid var(--cx-divider);
1451
+ border: 1px solid var(--cx-border-medium); /* Figma border/medium */
1247
1452
  border-radius: 24px;
1248
1453
  box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
1249
1454
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
@@ -1297,7 +1502,6 @@ button.__crossx-connect-other-block:active {
1297
1502
  height: 24px;
1298
1503
  flex-shrink: 0;
1299
1504
  border-radius: 0;
1300
- color: var(--cx-label);
1301
1505
  }
1302
1506
  .__crossx-card--wallet-selector .__crossx-close svg {
1303
1507
  width: 24px;
@@ -1422,7 +1626,7 @@ button.__crossx-connect-other-block:active {
1422
1626
  font-size: 16px;
1423
1627
  font-weight: 600;
1424
1628
  line-height: 1.5;
1425
- color: var(--cx-value);
1629
+ color: var(--cx-content-high); /* Figma content/high */
1426
1630
  letter-spacing: -0.01em;
1427
1631
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1428
1632
  white-space: nowrap;
@@ -1460,7 +1664,7 @@ button.__crossx-connect-other-block:active {
1460
1664
  align-items: center;
1461
1665
  justify-content: center;
1462
1666
  gap: 8px;
1463
- padding: 16px;
1667
+ padding: 15px 16px; /* Figma 높이 56 (보더 1px 포함) */
1464
1668
  border: 1px dashed var(--cx-border-medium); /* Figma border/medium */
1465
1669
  border-radius: 12px;
1466
1670
  cursor: pointer;
@@ -1476,10 +1680,10 @@ button.__crossx-connect-other-block:active {
1476
1680
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1477
1681
  transition: background-color 0.15s ease, border-color 0.15s ease, transform 0.1s ease;
1478
1682
  }
1479
- .__crossx-wallet-add:hover {
1683
+ .__crossx-wallet-add:hover:not(:disabled) {
1480
1684
  background: var(--cx-pill-bg);
1481
1685
  }
1482
- .__crossx-wallet-add:active {
1686
+ .__crossx-wallet-add:active:not(:disabled) {
1483
1687
  background: var(--cx-surface-high);
1484
1688
  transform: scale(0.99);
1485
1689
  }
@@ -1498,7 +1702,18 @@ button.__crossx-connect-other-block:active {
1498
1702
  font-weight: 500;
1499
1703
  line-height: 1.5;
1500
1704
  letter-spacing: -0.01em;
1501
- color: var(--cx-value);
1705
+ color: var(--cx-content-high); /* Figma content/high */
1706
+ }
1707
+ .__crossx-wallet-empty {
1708
+ margin: 0;
1709
+ padding: 16px;
1710
+ border-radius: 12px;
1711
+ background: var(--cx-pill-bg);
1712
+ color: var(--cx-subtitle);
1713
+ font-size: 14px;
1714
+ line-height: 1.5;
1715
+ text-align: center;
1716
+ word-break: keep-all;
1502
1717
  }
1503
1718
  .__crossx-wallet-add-error {
1504
1719
  margin: 8px 0 0;
@@ -1521,7 +1736,7 @@ button.__crossx-connect-other-block:active {
1521
1736
  box-sizing: border-box;
1522
1737
  }
1523
1738
  .__crossx-wallet-help-section .__crossx-mig-info-title {
1524
- color: var(--cx-value);
1739
+ color: var(--cx-content-high); /* Figma content/high */
1525
1740
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1526
1741
  font-size: 14px;
1527
1742
  font-weight: 600;
@@ -1542,8 +1757,82 @@ button.__crossx-connect-other-block:active {
1542
1757
  display: none;
1543
1758
  }
1544
1759
  /* ── Mobile bottom sheet ───────────────────────────────────── */
1760
+ /* ── 서명·전송 모달: Figma 「트랜잭션모달」 ──────────────────────────
1761
+ 폭 480, 본문 패딩 24 · 간격 24, 서브타이틀↔주소 24 · 주소↔경고 12, 마지막 행↔버튼 36(24+12).
1762
+ 모바일은 뒤의 \`.__crossx-card { width: 100% }\` 가, 가로 게임 화면은 아래 media 제외로 기존 규칙이 유지된다. */
1763
+ .__crossx-card--sign-tx,
1764
+ .__crossx-card--sign-msg,
1765
+ .__crossx-card--sign-typed,
1766
+ .__crossx-card--send-tx {
1767
+ width: 480px;
1768
+ }
1769
+ @media not all and (orientation: landscape) and (max-height: 500px) {
1770
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-title {
1771
+ margin-bottom: 0;
1772
+ }
1773
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-body {
1774
+ padding-top: 24px;
1775
+ }
1776
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-body-cols {
1777
+ gap: 24px;
1778
+ }
1779
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-col-left {
1780
+ gap: 24px;
1781
+ }
1782
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-addr-pill + .__crossx-warning {
1783
+ margin-top: -12px;
1784
+ }
1785
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-btn-row {
1786
+ margin-top: 20px;
1787
+ }
1788
+ /* 단일 확인 버튼(전송 승인 등)도 마지막 블록과 36(24+12) */
1789
+ :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-body > .__crossx-approve-btn {
1790
+ margin-top: 20px;
1791
+ }
1792
+ /* 전송 승인: 안내 문구 ↔ 상세 24 */
1793
+ .__crossx-card--send-tx .__crossx-tx-subtitle {
1794
+ margin-bottom: 8px;
1795
+ }
1796
+ }
1797
+ /* 주소 pill 지갑 아이콘 — Figma 20 · content/medium */
1798
+ .__crossx-addr-pill > svg {
1799
+ width: 20px;
1800
+ height: 20px;
1801
+ flex-shrink: 0;
1802
+ color: var(--cx-subtitle);
1803
+ }
1804
+ /* Figma lucide/copy 16 */
1805
+ .__crossx-row-value .__crossx-copy-btn svg,
1806
+ .__crossx-td-value .__crossx-copy-btn svg {
1807
+ width: 16px;
1808
+ height: 16px;
1809
+ }
1810
+
1811
+ /* ── CTA 버튼 텍스트 세로 중앙 고정 ─────────────────────────────
1812
+ 높이만 지정한 버튼(.__crossx-pw-btn, .__crossx-wallet-created-btn)은 호스트 페이지의
1813
+ 전역 \`button { padding }\` 이 새어 들어와 텍스트가 아래로 밀렸다(예: 15px 30px → 3px 처짐).
1814
+ 모든 CTA 를 flex 중앙 정렬 + 대칭 패딩으로 고정해 호스트 CSS 와 무관하게 가운데에 둔다. */
1815
+ /* 모든 CTA 공통 규격(단일 출처): 가운데 정렬 · 높이 48 · 좌우 16 · 16/600 · 줄높이 1.5 */
1816
+ .__crossx-pw-btn,
1817
+ .__crossx-wallet-created-btn,
1818
+ .__crossx-pin6-next,
1819
+ .__crossx-approve-btn,
1820
+ .__crossx-confirm-btn,
1821
+ .__crossx-cancel-btn {
1822
+ display: flex;
1823
+ align-items: center;
1824
+ justify-content: center;
1825
+ box-sizing: border-box;
1826
+ text-align: center;
1827
+ height: 48px;
1828
+ padding: 0 16px;
1829
+ font-size: 16px;
1830
+ font-weight: 600;
1831
+ line-height: 1.5;
1832
+ }
1833
+
1545
1834
  @media (max-width: 480px) {
1546
- #${re} {
1835
+ #${Y} {
1547
1836
  align-items: flex-end;
1548
1837
  /*
1549
1838
  * iOS Safari 는 soft keyboard 가 떠도 layout viewport 를 축소시키지 않아
@@ -1581,7 +1870,7 @@ button.__crossx-connect-other-block:active {
1581
1870
  overflow: hidden !important;
1582
1871
  display: flex !important;
1583
1872
  flex-direction: column !important;
1584
- border: 1px solid var(--cx-divider) !important;
1873
+ border: 1px solid var(--cx-border-medium) !important; /* Figma border/medium */
1585
1874
  border-bottom: none !important;
1586
1875
  border-radius: 24px 24px 0 0 !important;
1587
1876
  max-height: 85vh;
@@ -1646,7 +1935,10 @@ button.__crossx-connect-other-block:active {
1646
1935
  .__crossx-card--wallet-created .__crossx-close {
1647
1936
  display: none;
1648
1937
  }
1649
- .__crossx-wallet-created-sheet-handle {
1938
+ /* 헤더 border-bottom 이 구분선 역할 — hr 까지 보이면 선이 두 줄 */
1939
+ .__crossx-card--wallet-created > .__crossx-divider { display: none; }
1940
+ /* 기본 규칙(뒤에 선언)보다 우선하도록 카드 클래스를 앞에 붙인다 */
1941
+ .__crossx-card--wallet-created .__crossx-wallet-created-sheet-handle {
1650
1942
  display: block;
1651
1943
  width: 30px;
1652
1944
  height: 6px;
@@ -1654,13 +1946,13 @@ button.__crossx-connect-other-block:active {
1654
1946
  background: var(--cx-surface-high);
1655
1947
  flex-shrink: 0;
1656
1948
  }
1657
- .__crossx-wallet-created-body {
1949
+ .__crossx-card--wallet-created .__crossx-wallet-created-body {
1658
1950
  padding: 20px 16px;
1659
1951
  }
1660
- .__crossx-wallet-created-hero {
1952
+ .__crossx-card--wallet-created .__crossx-wallet-created-hero {
1661
1953
  height: 285px;
1662
1954
  }
1663
- .__crossx-wallet-created-footer {
1955
+ .__crossx-card--wallet-created .__crossx-wallet-created-footer {
1664
1956
  padding: 12px 16px 16px;
1665
1957
  }
1666
1958
  .__crossx-card--send-tx,
@@ -1693,9 +1985,71 @@ button.__crossx-connect-other-block:active {
1693
1985
  .__crossx-login-btn-row {
1694
1986
  flex-direction: column;
1695
1987
  }
1988
+ /* 모바일: 버튼은 세로로 쌓고, 버튼 안은 아이콘+텍스트 가로 정렬(가운데) */
1989
+ .__crossx-login-btn {
1990
+ flex-direction: row;
1991
+ gap: 8px;
1992
+ }
1993
+ .__crossx-login-icon {
1994
+ width: 28px;
1995
+ height: 28px;
1996
+ }
1997
+ .__crossx-login-icon svg {
1998
+ width: 28px;
1999
+ height: 28px;
2000
+ }
2001
+ .__crossx-login-btn-label {
2002
+ font-size: 16px;
2003
+ }
1696
2004
  .__crossx-login-btn-label {
1697
2005
  white-space: normal;
1698
2006
  }
2007
+ .__crossx-card--login .__crossx-body {
2008
+ padding: 16px;
2009
+ }
2010
+ /* Figma 모바일 시트 헤더: 손잡이 + 여백 16, X 없음(배경 탭·Esc 로 닫힘) */
2011
+ .__crossx-card--login .__crossx-header {
2012
+ display: flex;
2013
+ flex-direction: column;
2014
+ align-items: center;
2015
+ gap: 16px;
2016
+ padding: 16px;
2017
+ }
2018
+ .__crossx-card--login .__crossx-login-sheet-handle {
2019
+ display: block;
2020
+ width: 30px;
2021
+ height: 6px;
2022
+ border-radius: 9999px;
2023
+ background: var(--cx-surface-high);
2024
+ flex-shrink: 0;
2025
+ }
2026
+ .__crossx-card--login .__crossx-login-title-wrap {
2027
+ width: 100%;
2028
+ padding-right: 0 !important;
2029
+ }
2030
+ .__crossx-card--login .__crossx-close { display: none; }
2031
+ /* ── 모든 모달 모바일 시트 헤더 통일 (로그인·PIN·지갑 생성과 같은 방식) ──
2032
+ 손잡이(30×6) + 여백 16, 우상단 X 숨김. 손잡이는 ::before 로 그려 마크업을 바꾸지 않는다.
2033
+ 닫기는 배경 탭(백드롭)·본문 버튼으로 가능하다. 비밀번호 화면(--password)은 X 외 취소 수단이
2034
+ 없어 제외한다. 로그인·PIN·지갑 생성·지갑 선택은 자체 손잡이가 있어 제외. */
2035
+ :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header {
2036
+ display: flex;
2037
+ flex-direction: column;
2038
+ align-items: stretch;
2039
+ padding: 16px;
2040
+ }
2041
+ :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header::before {
2042
+ content: '';
2043
+ align-self: center;
2044
+ width: 30px;
2045
+ height: 6px;
2046
+ margin-bottom: 16px;
2047
+ border-radius: 9999px;
2048
+ background: var(--cx-surface-high);
2049
+ flex-shrink: 0;
2050
+ }
2051
+ :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header > .__crossx-close { display: none; }
2052
+ :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header .__crossx-title { padding-right: 0 !important; }
1699
2053
  /* ── Password card: mobile bottom sheet ── */
1700
2054
  .__crossx-card--password {
1701
2055
  width: 100% !important;
@@ -1762,7 +2116,8 @@ button.__crossx-connect-other-block:active {
1762
2116
  padding-right: 0 !important;
1763
2117
  }
1764
2118
  .__crossx-card--pin6 .__crossx-close { display: none; }
1765
- .__crossx-pin6-sheet-handle {
2119
+ /* 기본 규칙이 이 media 블록보다 뒤에 선언돼 있어 카드 클래스로 우선순위를 올린다 */
2120
+ .__crossx-card--pin6 .__crossx-pin6-sheet-handle {
1766
2121
  display: block;
1767
2122
  width: 30px;
1768
2123
  height: 6px;
@@ -1770,9 +2125,14 @@ button.__crossx-connect-other-block:active {
1770
2125
  background: var(--cx-surface-high);
1771
2126
  flex-shrink: 0;
1772
2127
  }
1773
- .__crossx-card--pin6 .__crossx-pw-subtitle { display: none; }
1774
- /* Notice 화면 body (pw-body) */
1775
- .__crossx-card--pin6 .__crossx-pw-body {
2128
+ /* Figma: 헤더 부제목 노출 — 제목과 4px 간격(헤더 gap 16 - 12), 좌측 정렬 */
2129
+ .__crossx-card--pin6 .__crossx-header .__crossx-pw-subtitle,
2130
+ .__crossx-card--pin6 .__crossx-header .__crossx-pin6-header-sub {
2131
+ width: 100%;
2132
+ margin-top: -12px;
2133
+ }
2134
+ /* Notice 화면 body (pw-body) — 기본 규칙(뒤에 선언)보다 우선하도록 카드 클래스를 겹친다 */
2135
+ .__crossx-card.__crossx-card--pin6 .__crossx-pw-body {
1776
2136
  flex: 1;
1777
2137
  min-height: 0;
1778
2138
  overflow-y: auto;
@@ -1786,12 +2146,16 @@ button.__crossx-connect-other-block:active {
1786
2146
  overflow-y: auto;
1787
2147
  -webkit-overflow-scrolling: touch;
1788
2148
  }
1789
- .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 18px; }
1790
- .__crossx-card--pin6 .__crossx-pw-notice-icon { width: 20px; height: 20px; }
2149
+ .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 16px; }
1791
2150
  .__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
1792
2151
  .__crossx-card--pin6 .__crossx-pin6-footer {
1793
2152
  padding: 12px 16px 16px;
1794
2153
  }
2154
+ /* Figma 시트: 홈 인디케이터 없이 하단 여백 20 */
2155
+ .__crossx-card.__crossx-card--pin6 {
2156
+ padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 20px);
2157
+ }
2158
+ .__crossx-card--pin6 .__crossx-home-indicator { display: none; }
1795
2159
  /* PIN 입력 body */
1796
2160
  .__crossx-card--pin6 .__crossx-pin6-body {
1797
2161
  flex: 1;
@@ -1842,7 +2206,7 @@ button.__crossx-connect-other-block:active {
1842
2206
 
1843
2207
  /* ── Landscape for signing/transaction modals ──────────── */
1844
2208
  @media (orientation: landscape) and (max-height: 500px) {
1845
- #${re} { align-items: center !important; overflow: hidden; }
2209
+ #${Y} { align-items: center !important; overflow: hidden; }
1846
2210
  .__crossx-card--send-tx,
1847
2211
  .__crossx-card--sign-tx,
1848
2212
  .__crossx-card--sign-msg,
@@ -1982,7 +2346,7 @@ button.__crossx-connect-other-block:active {
1982
2346
  overflow-y: auto;
1983
2347
  -webkit-overflow-scrolling: touch;
1984
2348
  }
1985
- .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 18px; }
2349
+ .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 16px; }
1986
2350
  .__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
1987
2351
  .__crossx-card--pin6 .__crossx-pin6-body {
1988
2352
  flex: 1;
@@ -2095,7 +2459,7 @@ button.__crossx-connect-other-block:active {
2095
2459
  gap: 8px;
2096
2460
  align-items: center;
2097
2461
  justify-content: center;
2098
- padding: 8px 0;
2462
+ padding: 0;
2099
2463
  }
2100
2464
  .__crossx-pin6-box {
2101
2465
  width: clamp(36px, 12vw, 48px);
@@ -2186,17 +2550,14 @@ button.__crossx-connect-other-block:active {
2186
2550
  /* Next 버튼 */
2187
2551
  .__crossx-pin6-next {
2188
2552
  width: 100%;
2189
- padding: 16px;
2190
2553
  background: var(--cx-primary-gradient);
2191
- color: #ffffff;
2554
+ color: var(--cx-on-primary);
2192
2555
  border: none;
2193
2556
  border-radius: 12px;
2194
- font-size: 18px;
2195
- font-weight: 700;
2196
2557
  cursor: pointer;
2197
- line-height: 1.3;
2198
2558
  transition: opacity 0.15s;
2199
2559
  -webkit-tap-highlight-color: transparent;
2560
+ height: 48px;
2200
2561
  }
2201
2562
  .__crossx-pin6-next:disabled,
2202
2563
  .__crossx-pin6-next.--disabled {
@@ -2210,7 +2571,7 @@ button.__crossx-connect-other-block:active {
2210
2571
  gap: 8px;
2211
2572
  align-items: center;
2212
2573
  justify-content: center;
2213
- padding: 8px 0;
2574
+ padding: 0; /* Figma: 안내문과 간격 16 (body gap) */
2214
2575
  }
2215
2576
  .__crossx-pin6-dot {
2216
2577
  width: clamp(36px, 12vw, 48px);
@@ -2286,8 +2647,8 @@ button.__crossx-connect-other-block:active {
2286
2647
  box-shadow: 0 1px 0 0 var(--cx-divider) !important;
2287
2648
  filter: none !important;
2288
2649
  }
2289
- .__crossx-pin6-numpad-key:active,
2290
- .__crossx-pin6-numpad-key.--pressed {
2650
+ .__crossx-pin6-numpad-key:active:not(.--disabled),
2651
+ .__crossx-pin6-numpad-key.--pressed:not(.--disabled) {
2291
2652
  background: var(--cx-input-border);
2292
2653
  }
2293
2654
  .__crossx-pin6-numpad-key.--empty {
@@ -2317,21 +2678,15 @@ button.__crossx-connect-other-block:active {
2317
2678
  align-items: center;
2318
2679
  width: 100%;
2319
2680
  }
2681
+ /* 헤더 제목과 같은 문구가 본문에 한 번 더 나온다 — Figma 4045:14458 에는 없어 숨긴다(마크업 유지) */
2320
2682
  .__crossx-session-hero-title {
2321
- font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
2322
- font-size: 24px;
2323
- font-weight: 600;
2324
- line-height: 1.3;
2325
- color: var(--cx-error);
2326
- text-align: center;
2327
- margin: 0;
2683
+ display: none;
2328
2684
  }
2329
2685
  .__crossx-session-hero-message {
2330
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
2331
- font-size: 14px;
2686
+ font-size: 16px;
2332
2687
  font-weight: 400;
2333
- line-height: 1.4;
2334
- color: var(--cx-title);
2688
+ line-height: 1.5;
2689
+ color: var(--cx-subtitle);
2335
2690
  text-align: center;
2336
2691
  margin: 0;
2337
2692
  white-space: pre-line;
@@ -2339,28 +2694,27 @@ button.__crossx-connect-other-block:active {
2339
2694
  .__crossx-session-account-card {
2340
2695
  background: var(--cx-pill-bg);
2341
2696
  border-radius: 12px;
2342
- padding: 20px;
2697
+ padding: 16px;
2343
2698
  display: flex;
2344
2699
  flex-direction: column;
2345
- gap: 12px;
2700
+ gap: 8px;
2346
2701
  align-items: center;
2347
2702
  width: 100%;
2348
2703
  box-sizing: border-box;
2349
2704
  }
2350
2705
  .__crossx-session-account-label {
2351
- font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
2352
- font-size: 15px;
2706
+ font-size: 14px;
2353
2707
  font-weight: 600;
2354
- line-height: 1.3;
2355
- color: var(--cx-label);
2708
+ line-height: 1.5;
2709
+ color: var(--cx-close);
2356
2710
  margin: 0;
2357
2711
  }
2358
2712
  .__crossx-session-account-email {
2359
- font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
2360
- font-size: 20px;
2713
+ font-size: 18px;
2361
2714
  font-weight: 600;
2362
- line-height: 1.3;
2363
- color: var(--cx-title);
2715
+ line-height: 1.5;
2716
+ color: var(--cx-content-high);
2717
+ word-break: break-all;
2364
2718
  margin: 0;
2365
2719
  }
2366
2720
 
@@ -2371,6 +2725,10 @@ button.__crossx-connect-other-block:active {
2371
2725
  display: flex;
2372
2726
  flex-direction: column;
2373
2727
  }
2728
+ /* Figma: 제목만 있는 헤더 — 제목 아래 4px 여백 없음 (헤더 높이 73) */
2729
+ .__crossx-card--wallet-created .__crossx-title {
2730
+ margin-bottom: 0;
2731
+ }
2374
2732
  .__crossx-wallet-created-sheet-handle {
2375
2733
  display: none;
2376
2734
  }
@@ -2386,171 +2744,7 @@ button.__crossx-connect-other-block:active {
2386
2744
  justify-content: center;
2387
2745
  width: 100%;
2388
2746
  }
2389
- .__crossx-wallet-created-illust {
2390
- display: block;
2391
- width: 204px;
2392
- height: 156px;
2393
- position: relative;
2394
- }
2395
- .__crossx-wallet-created-shadow {
2396
- position: absolute;
2397
- left: 60px;
2398
- bottom: 7px;
2399
- width: 84px;
2400
- height: 22px;
2401
- border-radius: 50%;
2402
- background: rgba(0,0,0,0.65);
2403
- }
2404
- .__crossx-wallet-created-wallet {
2405
- position: absolute;
2406
- left: 55px;
2407
- top: 58px;
2408
- width: 94px;
2409
- height: 64px;
2410
- border-radius: 13px;
2411
- background: #6D4CFF;
2412
- }
2413
- .__crossx-wallet-created-wallet::before {
2414
- content: '';
2415
- position: absolute;
2416
- left: 11px;
2417
- top: 12px;
2418
- width: 72px;
2419
- height: 15px;
2420
- border-radius: 4px;
2421
- background: #00CEB2;
2422
- }
2423
- .__crossx-wallet-created-wallet::after {
2424
- content: '';
2425
- position: absolute;
2426
- left: 11px;
2427
- top: 30px;
2428
- width: 72px;
2429
- height: 12px;
2430
- border-radius: 3px;
2431
- background: #FFFFFF;
2432
- }
2433
- .__crossx-wallet-created-coin {
2434
- position: absolute;
2435
- left: 52px;
2436
- top: 74px;
2437
- width: 30px;
2438
- height: 30px;
2439
- border-radius: 50%;
2440
- background: #00CEB2;
2441
- }
2442
- .__crossx-wallet-created-coin::before,
2443
- .__crossx-wallet-created-coin::after {
2444
- content: '';
2445
- position: absolute;
2446
- height: 3px;
2447
- border-radius: 9999px;
2448
- background: #FFFFFF;
2449
- transform: rotate(-28deg);
2450
- }
2451
- .__crossx-wallet-created-coin::before {
2452
- left: 6px;
2453
- top: 13px;
2454
- width: 18px;
2455
- }
2456
- .__crossx-wallet-created-coin::after {
2457
- left: 10px;
2458
- top: 18px;
2459
- width: 14px;
2460
- }
2461
- .__crossx-wallet-created-burst {
2462
- position: absolute;
2463
- left: 124px;
2464
- top: 30px;
2465
- width: 30px;
2466
- height: 30px;
2467
- border-radius: 50%;
2468
- background: #FF5D85;
2469
- }
2470
- .__crossx-wallet-created-burst::before,
2471
- .__crossx-wallet-created-burst::after {
2472
- content: '';
2473
- position: absolute;
2474
- left: 7px;
2475
- top: 13px;
2476
- width: 16px;
2477
- height: 3px;
2478
- border-radius: 9999px;
2479
- background: #FFFFFF;
2480
- }
2481
- .__crossx-wallet-created-burst::after {
2482
- transform: rotate(90deg);
2483
- }
2484
- .__crossx-wallet-created-pointer {
2485
- position: absolute;
2486
- left: 147px;
2487
- top: 90px;
2488
- width: 28px;
2489
- height: 28px;
2490
- border-radius: 50%;
2491
- background: #FFFFFF;
2492
- border: 2px solid rgba(0,0,0,0.18);
2493
- }
2494
- .__crossx-wallet-created-pointer::before {
2495
- content: '';
2496
- position: absolute;
2497
- left: 8px;
2498
- top: 7px;
2499
- width: 12px;
2500
- height: 12px;
2501
- background: #252B39;
2502
- clip-path: polygon(0 36%, 100% 0, 62% 100%, 43% 62%);
2503
- }
2504
- .__crossx-wallet-created-sparkle {
2505
- position: absolute;
2506
- width: 14px;
2507
- height: 14px;
2508
- }
2509
- .__crossx-wallet-created-sparkle::before,
2510
- .__crossx-wallet-created-sparkle::after {
2511
- content: '';
2512
- position: absolute;
2513
- border-radius: 9999px;
2514
- background: currentColor;
2515
- }
2516
- .__crossx-wallet-created-sparkle::before {
2517
- left: 6px;
2518
- top: 0;
2519
- width: 3px;
2520
- height: 14px;
2521
- }
2522
- .__crossx-wallet-created-sparkle::after {
2523
- left: 0;
2524
- top: 6px;
2525
- width: 14px;
2526
- height: 3px;
2527
- }
2528
- .__crossx-wallet-created-sparkle--purple {
2529
- left: 126px;
2530
- top: 22px;
2531
- color: #8D79FF;
2532
- transform: rotate(26deg);
2533
- }
2534
- .__crossx-wallet-created-sparkle--teal {
2535
- left: 32px;
2536
- top: 108px;
2537
- color: #00CEB2;
2538
- }
2539
- .__crossx-wallet-created-dot {
2540
- position: absolute;
2541
- width: 6px;
2542
- height: 6px;
2543
- border-radius: 50%;
2544
- background: #BFD0EA;
2545
- }
2546
- .__crossx-wallet-created-dot--one {
2547
- left: 122px;
2548
- top: 34px;
2549
- }
2550
- .__crossx-wallet-created-dot--two {
2551
- left: 178px;
2552
- top: 87px;
2553
- }
2747
+ ${vc}
2554
2748
  .__crossx-wallet-created-footer {
2555
2749
  padding: 12px 24px 24px;
2556
2750
  width: 100%;
@@ -2558,15 +2752,11 @@ button.__crossx-connect-other-block:active {
2558
2752
  }
2559
2753
  .__crossx-wallet-created-btn {
2560
2754
  width: 100%;
2561
- height: 48px;
2562
2755
  border: none;
2563
2756
  border-radius: 12px;
2564
2757
  background: var(--cx-primary-gradient);
2565
- color: #ffffff;
2758
+ color: var(--cx-on-primary);
2566
2759
  font-family: inherit;
2567
- font-size: 16px;
2568
- font-weight: 600;
2569
- line-height: 1.5;
2570
2760
  letter-spacing: -0.01em;
2571
2761
  cursor: pointer;
2572
2762
  }
@@ -2579,7 +2769,7 @@ button.__crossx-connect-other-block:active {
2579
2769
  filter: none !important;
2580
2770
  transform: none !important;
2581
2771
  background: var(--cx-primary-gradient) !important;
2582
- color: #ffffff !important;
2772
+ color: var(--cx-on-primary) !important;
2583
2773
  }
2584
2774
 
2585
2775
  /* ── Amount tooltip ──────────────────────────────────────────────── */
@@ -2604,28 +2794,25 @@ button.__crossx-connect-other-block:active {
2604
2794
  .__crossx-tip-overlay.--visible {
2605
2795
  display: block;
2606
2796
  }
2607
- `;function de(){let s=document.getElementById(rn);s||(s=document.createElement("style"),s.id=rn,document.head.appendChild(s)),s.textContent=Fa}function Ua(){const s=`#${re}`,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 ue(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=Ua(),n=Wa(s),i=s.remove.bind(s);s.remove=()=>{n(),t(),i()},document.body.appendChild(s)}function Wa(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 Ha(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,_=c.top-u-6;p<8&&(p=8),_<8&&(_=c.bottom+6),r.style.left=`${p}px`,r.style.top=`${_}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 Ka=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function $e(){if(Ka()){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 Ie(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function nn(s){return s?s.length<=13?s:`${s.slice(0,6)}...${s.slice(-4)}`:"—"}function on(s,e="ONE",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=gr(n,r,t);if(i==="0")return null;const o=fr(n,r);return _r(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const an={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"ONEchain Testnet",612055:"CROSS Mainnet"},ur=new Map;let hr=!1;function Ga(){if(hr||(hr=!0,typeof fetch>"u"))return;const s=Bt().contentsBaseUrl;s&&fetch(`${s}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,n]of Object.entries(r)){const i=Number(t);!Number.isNaN(i)&&n&&ur.set(i,n)}}).catch(()=>{hr=!1})}function cn(s){return parseInt(s.split(":")[1]??"",10)}function ln(s){var r;const e=cn(s);if(!isNaN(e)){const t=(r=ur.get(e))==null?void 0:r.name;if(t)return t;if(an[e])return an[e]}return s}function pr(s,e){var r;if(s){const t=cn(s);if(!isNaN(t)){const n=(r=ur.get(t))==null?void 0:r.nativeSymbol;if(n)return n}}return e}function fr(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 _r(s,e){return s===e?v(s):`<span class="__crossx-amount-tip" data-full="${v(e)}">${v(s)}</span>`}function gr(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 xr(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 Va(s){try{return BigInt(s).toLocaleString()}catch{return s}}function qa(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeDecimals:o=18}=s,a=pr(s.chainId,s.nativeSymbol??"ETH");if(!r)return null;try{const c=BigInt(r),l=Va(r);if(n){const u=c*BigInt(n);return{isDynamic:!0,estTxFee:_r(`${gr(u,o,e)} ${a}`,`${fr(u,o)} ${a}`),maxFeeGwei:xr(n),maxPriorityFeeGwei:i?xr(i):void 0,gasLimitFormatted:l}}if(t){const u=c*BigInt(t);return{isDynamic:!1,estTxFee:_r(`${gr(u,o,e)} ${a}`,`${fr(u,o)} ${a}`),gasPriceGwei:xr(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function dn(s,e,r){const t=qa(s,e);if(!t)return ee((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=ee((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=ee((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=ee((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=ee((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=ee((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),n}const Re=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2797
+ `;function le(){let s=document.getElementById(vn);s||(s=document.createElement("style"),s.id=vn,document.head.appendChild(s)),s.textContent=Ac}function Tc(){const s=`#${Y}`,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 de(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=Tc(),n=Rc(s),i=s.remove.bind(s);s.remove=()=>{n(),t(),i()},document.body.appendChild(s)}function Rc(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 Nc(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,d=r.offsetHeight;let p=c.right-l,f=c.top-d-6;p<8&&(p=8),f<8&&(f=c.bottom+6),r.style.left=`${p}px`,r.style.top=`${f}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 Cc=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Le(){if(Cc()){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 Ae(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function In(s){return s?s.length<=13?s:`${s.slice(0,6)}...${s.slice(-4)}`:"—"}function An(s,e="ONE",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=Ar(n,r,t);if(i==="0")return null;const o=Er(n,r);return Ir(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const Tn={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"ONEchain Testnet",612055:"CROSS Mainnet"},br=new Map;let Sr=!1;function Oc(){if(Sr||(Sr=!0,typeof fetch>"u"))return;const s=wt().contentsBaseUrl;s&&fetch(`${s}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,n]of Object.entries(r)){const i=Number(t);!Number.isNaN(i)&&n&&br.set(i,n)}}).catch(()=>{Sr=!1})}function Rn(s){return parseInt(s.split(":")[1]??"",10)}function Nn(s){var r;const e=Rn(s);if(!isNaN(e)){const t=(r=br.get(e))==null?void 0:r.name;if(t)return t;if(Tn[e])return Tn[e]}return s}function vr(s,e){var r;if(s){const t=Rn(s);if(!isNaN(t)){const n=(r=br.get(t))==null?void 0:r.nativeSymbol;if(n)return n}}return e}function Er(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 Ir(s,e){return s===e?v(s):`<span class="__crossx-amount-tip" data-full="${v(e)}">${v(s)}</span>`}function Ar(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 Tr(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 kc(s){try{return BigInt(s).toLocaleString()}catch{return s}}function Pc(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeDecimals:o=18}=s,a=vr(s.chainId,s.nativeSymbol??"ETH");if(!r)return null;try{const c=BigInt(r),l=kc(r);if(n){const d=c*BigInt(n);return{isDynamic:!0,estTxFee:Ir(`${Ar(d,o,e)} ${a}`,`${Er(d,o)} ${a}`),maxFeeGwei:Tr(n),maxPriorityFeeGwei:i?Tr(i):void 0,gasLimitFormatted:l}}if(t){const d=c*BigInt(t);return{isDynamic:!1,estTxFee:Ir(`${Ar(d,o,e)} ${a}`,`${Er(d,o)} ${a}`),gasPriceGwei:Tr(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function Cn(s,e,r){const t=Pc(s,e);if(!t)return te((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=te((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=te((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=te((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=te((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=te((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),n}const Te=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2608
2798
  <rect x="9" y="9" width="13" height="13" rx="2"/>
2609
2799
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
2610
- </svg>`,oe=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2611
- <line x1="18" y1="6" x2="6" y2="18"/>
2612
- <line x1="6" y1="6" x2="18" y2="18"/>
2613
- </svg>`,za='<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>',Ja='<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>';function un(s,e){return`<svg width="${s}" height="${s}" viewBox="0 0 229 229" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><g clip-path="url(#clip0_${e})"><rect width="228.273" height="228.273" rx="87" fill="white"/><path d="M228.307 -0.0644531H0.0332031V228.209H228.307V-0.0644531Z" fill="#CE3E35"/><path d="M33.9219 43.7533C33.9219 31.934 43.5033 22.3527 55.3225 22.3527H173.019C184.838 22.3527 194.419 31.9341 194.419 43.7533V123.107H33.9219V43.7533Z" fill="white"/><g filter="url(#filter0_d_${e})"><path d="M228.241 228.21H0.0332031V56.5961C0.0332031 48.7166 6.4208 42.329 14.3003 42.329H77.9502C84.6851 42.329 90.1926 47.3831 94.2527 52.7566C98.8699 58.8676 106.06 62.7958 114.137 62.7958C122.214 62.7958 129.404 58.8676 134.021 52.7566C138.081 47.3831 143.589 42.329 150.324 42.329H213.974C221.854 42.329 228.241 48.7166 228.241 56.5961V228.21Z" fill="url(#paint0_linear_${e})"/></g><path d="M79.7598 228.096H228.24V64.7367L79.7598 159.851V228.096Z" fill="url(#paint1_linear_${e})"/><path d="M79.7694 228.209H0.0332031V75.9257L79.7694 160.218V228.209Z" fill="url(#paint2_linear_${e})"/><g filter="url(#filter1_d_${e})"><path d="M113.105 89.2908L81.3322 107.655C75.7279 110.878 73.7862 118.118 77.0076 123.724C80.229 129.331 87.4661 131.273 93.0704 128.051L119.945 112.511L107.147 126.241V180.098C107.147 186.588 112.443 191.885 118.93 191.885C125.417 191.885 130.712 186.588 130.712 180.098V99.4884C130.712 97.237 130.006 95.0297 129.124 93.5729C125.814 88.0106 118.665 86.024 113.061 89.2466L113.105 89.2908Z" fill="white"/></g></g><defs><filter id="filter0_d_${e}" x="-7.10034" y="33.4121" width="242.474" height="200.148" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dy="-1.78339"/><feGaussianBlur stdDeviation="3.56677"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.892803 0 0 0 0 0.220099 0 0 0 0 0.293135 0 0 0 0.5 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_${e}"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_${e}" result="shape"/></filter><filter id="filter1_d_${e}" x="67.9009" y="80.1489" width="75.3839" height="124.308" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="2.51084" dy="2.51084"/><feGaussianBlur stdDeviation="5.03056"/><feColorMatrix type="matrix" values="0 0 0 0 0.831373 0 0 0 0 0.113725 0 0 0 0 0.356863 0 0 0 0.3 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_${e}"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_${e}" result="shape"/></filter><linearGradient id="paint0_linear_${e}" x1="-26.3993" y1="19.4879" x2="193.409" y2="286.17" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="paint1_linear_${e}" x1="56.978" y1="73.7355" x2="168.096" y2="169.248" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="paint2_linear_${e}" x1="142.362" y1="29.5078" x2="37.3384" y2="166.255" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><clipPath id="clip0_${e}"><rect width="228.273" height="228.273" rx="87" fill="white"/></clipPath></defs></svg>`}const Ya=un(16,"connect-inline"),ja={[We.MetaMask]:za,[We.Binance]:Ja,[We.CROSSx]:Ya},hn='<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"/>',wr=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${hn}</svg>`,Xa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2800
+ </svg>`,ie='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6L18 18"/></svg>',Dc='<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>',Lc='<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>';function On(s,e){return`<svg width="${s}" height="${s}" viewBox="0 0 229 229" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><g clip-path="url(#clip0_${e})"><rect width="228.273" height="228.273" rx="87" fill="white"/><path d="M228.307 -0.0644531H0.0332031V228.209H228.307V-0.0644531Z" fill="#CE3E35"/><path d="M33.9219 43.7533C33.9219 31.934 43.5033 22.3527 55.3225 22.3527H173.019C184.838 22.3527 194.419 31.9341 194.419 43.7533V123.107H33.9219V43.7533Z" fill="white"/><g filter="url(#filter0_d_${e})"><path d="M228.241 228.21H0.0332031V56.5961C0.0332031 48.7166 6.4208 42.329 14.3003 42.329H77.9502C84.6851 42.329 90.1926 47.3831 94.2527 52.7566C98.8699 58.8676 106.06 62.7958 114.137 62.7958C122.214 62.7958 129.404 58.8676 134.021 52.7566C138.081 47.3831 143.589 42.329 150.324 42.329H213.974C221.854 42.329 228.241 48.7166 228.241 56.5961V228.21Z" fill="url(#paint0_linear_${e})"/></g><path d="M79.7598 228.096H228.24V64.7367L79.7598 159.851V228.096Z" fill="url(#paint1_linear_${e})"/><path d="M79.7694 228.209H0.0332031V75.9257L79.7694 160.218V228.209Z" fill="url(#paint2_linear_${e})"/><g filter="url(#filter1_d_${e})"><path d="M113.105 89.2908L81.3322 107.655C75.7279 110.878 73.7862 118.118 77.0076 123.724C80.229 129.331 87.4661 131.273 93.0704 128.051L119.945 112.511L107.147 126.241V180.098C107.147 186.588 112.443 191.885 118.93 191.885C125.417 191.885 130.712 186.588 130.712 180.098V99.4884C130.712 97.237 130.006 95.0297 129.124 93.5729C125.814 88.0106 118.665 86.024 113.061 89.2466L113.105 89.2908Z" fill="white"/></g></g><defs><filter id="filter0_d_${e}" x="-7.10034" y="33.4121" width="242.474" height="200.148" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dy="-1.78339"/><feGaussianBlur stdDeviation="3.56677"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.892803 0 0 0 0 0.220099 0 0 0 0 0.293135 0 0 0 0.5 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_${e}"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_${e}" result="shape"/></filter><filter id="filter1_d_${e}" x="67.9009" y="80.1489" width="75.3839" height="124.308" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="2.51084" dy="2.51084"/><feGaussianBlur stdDeviation="5.03056"/><feColorMatrix type="matrix" values="0 0 0 0 0.831373 0 0 0 0 0.113725 0 0 0 0 0.356863 0 0 0 0.3 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_${e}"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_${e}" result="shape"/></filter><linearGradient id="paint0_linear_${e}" x1="-26.3993" y1="19.4879" x2="193.409" y2="286.17" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="paint1_linear_${e}" x1="56.978" y1="73.7355" x2="168.096" y2="169.248" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="paint2_linear_${e}" x1="142.362" y1="29.5078" x2="37.3384" y2="166.255" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><clipPath id="clip0_${e}"><rect width="228.273" height="228.273" rx="87" fill="white"/></clipPath></defs></svg>`}const Bc=On(16,"connect-inline"),Mc={[We.MetaMask]:Dc,[We.Binance]:Lc,[We.CROSSx]:Bc},$c='<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"/>',Rr='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M17.4076 5.37036V3.51851C17.4076 2.49722 16.5771 1.66666 15.5558 1.66666H3.51874C1.98726 1.66666 0.740967 2.91296 0.740967 4.44444V15.5555C0.740967 17.5935 2.40208 18.3333 3.51874 18.3333H17.4076C18.4289 18.3333 19.2595 17.5028 19.2595 16.4815V7.22222C19.2595 6.20092 18.4289 5.37036 17.4076 5.37036ZM15.5558 13.7037H13.7039V9.99999H15.5558V13.7037ZM3.51874 5.37036C3.28034 5.3597 3.05523 5.25749 2.8903 5.08501C2.72536 4.91253 2.63331 4.68308 2.63331 4.44444C2.63331 4.20579 2.72536 3.97634 2.8903 3.80387C3.05523 3.63139 3.28034 3.52918 3.51874 3.51851H15.5558V5.37036H3.51874Z"/></svg>',Uc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2614
2801
  <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)"/>
2615
- </svg>`,Za=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2802
+ </svg>`,Fc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2616
2803
  <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
2617
2804
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
2618
2805
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
2619
- </svg>`;function ce(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-border-medium:${s.borderMedium}`,`--cx-title:${s.titleColor}`,`--cx-content-high:${s.contentHigh}`,`--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-primary-gradient:${s.primaryGradient}`,`--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 Qa(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-primary-gradient",e.primaryGradient),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 ee(s,e){return`
2806
+ </svg>`;function ce(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-border-medium:${s.borderMedium}`,`--cx-title:${s.titleColor}`,`--cx-content-high:${s.contentHigh}`,`--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-primary-gradient:${s.primaryGradient}`,`--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}`,`--cx-wc-sparkle:${s.sparkleColor}`,`--cx-warning:${s.warningColor}`].join(";")}function Wc(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-primary-gradient",e.primaryGradient),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),s.style.setProperty("--cx-wc-sparkle",e.sparkleColor),s.style.setProperty("--cx-warning",e.warningColor)}function te(s,e){return`
2620
2807
  <div class="__crossx-row">
2621
2808
  <span class="__crossx-row-label">${s}</span>
2622
2809
  <div class="__crossx-row-value">${e}</div>
2623
- </div>`}function ec(s,e,r,t){const n=e,i=pr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=Tt(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ie(s.to)}</span>
2624
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Re}</button>`:"<span>—</span>",l=dn(s,r,t),u=on(s.value,i,o,r),p=u?ee((t==null?void 0:t.label_value)??"Value",`<span>${u}</span>`):"",_=s.data??"0x",x=document.createElement("div");return x.id=re,x.innerHTML=`
2810
+ </div>`}function Hc(s,e,r,t){const n=e,i=vr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=Dt(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ae(s.to)}</span>
2811
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=Cn(s,r,t),d=An(s.value,i,o,r),p=d?te((t==null?void 0:t.label_value)??"Value",`<span>${d}</span>`):"",f=s.data??"0x",g=/^(0x)?$/i.test(f.trim())?"":`<pre class="__crossx-raw-tx">${v(f)}</pre>`,w=document.createElement("div");return w.id=Y,w.innerHTML=`
2625
2812
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ce(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2626
2813
  <div class="__crossx-header">
2627
2814
  <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
2628
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2815
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2629
2816
  </div>
2630
2817
  <hr class="__crossx-divider">
2631
2818
  <div class="__crossx-body">
@@ -2635,20 +2822,20 @@ button.__crossx-connect-other-block:active {
2635
2822
  <span class="__crossx-sig-origin">${v(a)}</span>${v((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
2636
2823
  </p>
2637
2824
  <div class="__crossx-addr-pill">
2638
- ${wr}
2639
- <span class="__crossx-addr-pill-text">${Ie(s.from)}</span>
2825
+ ${Rr}
2826
+ <span class="__crossx-addr-pill-text">${Ae(s.from)}</span>
2640
2827
  </div>
2641
2828
  <p class="__crossx-warning">${v((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2642
2829
  </div>
2643
2830
  <hr class="__crossx-divider __crossx-divider--cols">
2644
2831
  <div class="__crossx-col-right-sign">
2645
2832
  <div class="__crossx-rows">
2646
- ${ee((t==null?void 0:t.label_to)??"To",c)}
2647
- ${ee((t==null?void 0:t.label_network)??"Network",`<span>${ln(s.chainId)}</span>`)}
2833
+ ${te((t==null?void 0:t.label_to)??"To",c)}
2834
+ ${te((t==null?void 0:t.label_network)??"Network",`<span>${Nn(s.chainId)}</span>`)}
2648
2835
  ${p}
2649
2836
  ${l}
2650
2837
  </div>
2651
- <pre class="__crossx-raw-tx">${v(_)}</pre>
2838
+ ${g}
2652
2839
  </div>
2653
2840
  </div>
2654
2841
  <div class="__crossx-btn-row">
@@ -2657,12 +2844,12 @@ button.__crossx-connect-other-block:active {
2657
2844
  </div>
2658
2845
  </div>
2659
2846
  </div>
2660
- `,x}const tc=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function rc(s){return s?tc.has(s.slice(0,10).toLowerCase()):!1}function sc(s,e,r,t){const n=e,i=pr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=Tt(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ie(s.to)}</span>
2661
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Re}</button>`:"<span>—</span>",l=dn(s,r,t),p=on(s.value,i,o,r)??"—",_=rc(s.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",x=document.createElement("div");return x.id=re,x.innerHTML=`
2847
+ `,w}const Gc=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Kc(s){return s?Gc.has(s.slice(0,10).toLowerCase()):!1}function Vc(s,e,r,t){const n=e,i=vr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=Dt(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ae(s.to)}</span>
2848
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=Cn(s,r,t),p=An(s.value,i,o,r)??"—",f=Kc(s.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",g=document.createElement("div");return g.id=Y,g.innerHTML=`
2662
2849
  <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ce(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2663
2850
  <div class="__crossx-header">
2664
2851
  <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
2665
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2852
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2666
2853
  </div>
2667
2854
  <hr class="__crossx-divider">
2668
2855
  <div class="__crossx-body">
@@ -2671,29 +2858,29 @@ button.__crossx-connect-other-block:active {
2671
2858
  </p>
2672
2859
  <div class="__crossx-body-cols">
2673
2860
  <div class="__crossx-rows">
2674
- ${ee((t==null?void 0:t.label_to)??"To",c)}
2675
- ${ee((t==null?void 0:t.label_network)??"Network",`<span>${ln(s.chainId)}</span>`)}
2861
+ ${te((t==null?void 0:t.label_to)??"To",c)}
2862
+ ${te((t==null?void 0:t.label_network)??"Network",`<span>${Nn(s.chainId)}</span>`)}
2676
2863
  ${l}
2677
2864
  </div>
2678
2865
  <div class="__crossx-pill">
2679
- <span class="__crossx-pill-from">${Ie(s.from)}</span>
2866
+ <span class="__crossx-pill-from">${Ae(s.from)}</span>
2680
2867
  <span class="__crossx-pill-amount">${p}</span>
2681
2868
  </div>
2682
2869
  </div>
2683
- <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${v(_)}</button>
2870
+ <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${v(f)}</button>
2684
2871
  </div>
2685
2872
  </div>
2686
- `,x}function Tt(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function v(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function nc(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function ic(s){if(typeof s=="string")return v(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return v(JSON.stringify(s))}catch{return String(s)}}function oc(s){return s.includes(":")?s.split(":")[1]??s:s}function ac(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function cc(s,e){return`https://explorer.crosstoken.io/${oc(s)}/tx/${e}`}function pn(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${v(e)}" target="_blank" rel="noopener noreferrer">${v(s)}</a>`}function kt(s){return pn(Ie(s),ac(s))}function fn(s,e){return pn(Ie(e),cc(s,e))}function lc(s,e,r){const t=ee((r==null?void 0:r.label_from)??"From",`${kt(s.from)}
2687
- <button class="__crossx-copy-btn" data-copy="${v(s.from)}" title="Copy address">${Re}</button>`),n=s.to?ee((r==null?void 0:r.label_to)??"To",`${kt(s.to)}
2688
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Re}</button>`):"",i=s.amount?ee((r==null?void 0:r.label_transfer)??"Transfer",`<span>${v(s.amount)}</span>`):"",o=s.fees?ee((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${v(s.fees)}</span>`):"",a=s.txHash?ee((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${fn(s.chainId,s.txHash)}
2689
- <button class="__crossx-copy-btn" data-copy="${v(s.txHash)}" title="Copy hash">${Re}</button>`):"",c=s.total?`<div class="__crossx-total-pill">
2873
+ `,g}function Dt(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function v(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function qc(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function zc(s){if(typeof s=="string")return v(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return v(JSON.stringify(s))}catch{return String(s)}}function Jc(s){return s.includes(":")?s.split(":")[1]??s:s}function jc(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function Yc(s,e){return`https://explorer.crosstoken.io/${Jc(s)}/tx/${e}`}function kn(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${v(e)}" target="_blank" rel="noopener noreferrer">${v(s)}</a>`}function Lt(s){return kn(Ae(s),jc(s))}function Pn(s,e){return kn(Ae(e),Yc(s,e))}function Xc(s,e,r){const t=te((r==null?void 0:r.label_from)??"From",`${Lt(s.from)}
2874
+ <button class="__crossx-copy-btn" data-copy="${v(s.from)}" title="Copy address">${Te}</button>`),n=s.to?te((r==null?void 0:r.label_to)??"To",`${Lt(s.to)}
2875
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`):"",i=s.amount?te((r==null?void 0:r.label_transfer)??"Transfer",`<span>${v(s.amount)}</span>`):"",o=s.fees?te((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${v(s.fees)}</span>`):"",a=s.txHash?te((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${Pn(s.chainId,s.txHash)}
2876
+ <button class="__crossx-copy-btn" data-copy="${v(s.txHash)}" title="Copy hash">${Te}</button>`):"",c=s.total?`<div class="__crossx-total-pill">
2690
2877
  <span class="__crossx-total-label">${v((r==null?void 0:r.label_total)??"Total")}<br>${v((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
2691
2878
  <span class="__crossx-total-amount">${v(s.total)}</span>
2692
- </div>`:"",l=document.createElement("div");return l.id=re,l.innerHTML=`
2879
+ </div>`:"",l=document.createElement("div");return l.id=Y,l.innerHTML=`
2693
2880
  <div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2694
2881
  <div class="__crossx-header">
2695
2882
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
2696
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2883
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2697
2884
  </div>
2698
2885
  <hr class="__crossx-divider">
2699
2886
  <div class="__crossx-body">
@@ -2708,7 +2895,7 @@ button.__crossx-connect-other-block:active {
2708
2895
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
2709
2896
  </div>
2710
2897
  </div>
2711
- `,l}function dc(s,e,r){const t=document.createElement("div");return t.id=re,t.innerHTML=`
2898
+ `,l}function Zc(s,e,r){const t=document.createElement("div");return t.id=Y,t.innerHTML=`
2712
2899
  <div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2713
2900
  <div class="__crossx-header">
2714
2901
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
@@ -2721,27 +2908,27 @@ button.__crossx-connect-other-block:active {
2721
2908
  </div>
2722
2909
  </div>
2723
2910
  </div>
2724
- `,t}function uc(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 g=i?Za:n?"":Xa,m=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";g?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${g}<span>${v(m)}</span>`):o.textContent=m}if(a&&!s.querySelector("#__crossx-close-btn")){const g=document.createElement("button");g.className="__crossx-close",g.id="__crossx-close-btn",g.setAttribute("aria-label","Close"),g.innerHTML=oe,a.appendChild(g)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?ee((t==null?void 0:t.label_from)??"From",`${kt(e.from)}
2725
- <button class="__crossx-copy-btn" data-copy="${v(e.from)}" title="Copy address">${Re}</button>`):"",u=e.to?ee((t==null?void 0:t.label_to)??"To",`${kt(e.to)}
2726
- <button class="__crossx-copy-btn" data-copy="${v(e.to)}" title="Copy address">${Re}</button>`):"",p=e.amount?ee((t==null?void 0:t.label_transfer)??"Transfer",`<span>${v(e.amount)}</span>`):"",_=e.fees?ee((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${v(e.fees)}</span>`):"",x=e.txHash?ee((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${fn(e.chainId,e.txHash)}
2727
- <button class="__crossx-copy-btn" data-copy="${v(e.txHash)}" title="Copy hash">${Re}</button>`):"",w=e.total?`<div class="__crossx-total-pill">
2911
+ `,t}function Qc(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 m=i?Fc:n?"":Uc,x=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";m?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${m}<span>${v(x)}</span>`):o.textContent=x}if(a&&!s.querySelector("#__crossx-close-btn")){const m=document.createElement("button");m.className="__crossx-close",m.id="__crossx-close-btn",m.setAttribute("aria-label","Close"),m.innerHTML=ie,a.appendChild(m)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?te((t==null?void 0:t.label_from)??"From",`${Lt(e.from)}
2912
+ <button class="__crossx-copy-btn" data-copy="${v(e.from)}" title="Copy address">${Te}</button>`):"",d=e.to?te((t==null?void 0:t.label_to)??"To",`${Lt(e.to)}
2913
+ <button class="__crossx-copy-btn" data-copy="${v(e.to)}" title="Copy address">${Te}</button>`):"",p=e.amount?te((t==null?void 0:t.label_transfer)??"Transfer",`<span>${v(e.amount)}</span>`):"",f=e.fees?te((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${v(e.fees)}</span>`):"",g=e.txHash?te((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${Pn(e.chainId,e.txHash)}
2914
+ <button class="__crossx-copy-btn" data-copy="${v(e.txHash)}" title="Copy hash">${Te}</button>`):"",w=e.total?`<div class="__crossx-total-pill">
2728
2915
  <span class="__crossx-total-label">${v((t==null?void 0:t.label_total)??"Total")}<br>${v((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
2729
2916
  <span class="__crossx-total-amount">${v(e.total)}</span>
2730
2917
  </div>`:"";c.innerHTML=`
2731
2918
  <div class="__crossx-rows">
2732
2919
  ${l}
2733
- ${u}
2920
+ ${d}
2734
2921
  ${p}
2735
- ${_}
2736
- ${x}
2922
+ ${f}
2923
+ ${g}
2737
2924
  </div>
2738
2925
  ${w}
2739
2926
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((t==null?void 0:t.tx_complete_done_button)??(n?"All Done":"Done"))}</button>
2740
- `,c.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",m=>{var I;m.stopPropagation();const E=g.dataset.copy;E&&((I=navigator.clipboard)==null||I.writeText(E).catch(()=>{}))})})}function hc(s,e,r){const t=e,n=Tt(s.dappName),i=v(s.message),o=document.createElement("div");return o.id=re,o.innerHTML=`
2927
+ `,c.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",x=>{var I;x.stopPropagation();const S=m.dataset.copy;S&&((I=navigator.clipboard)==null||I.writeText(S).catch(()=>{}))})})}function el(s,e,r){const t=e,n=Dt(s.dappName),i=v(s.message),o=document.createElement("div");return o.id=Y,o.innerHTML=`
2741
2928
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2742
2929
  <div class="__crossx-header">
2743
2930
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
2744
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2931
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2745
2932
  </div>
2746
2933
  <hr class="__crossx-divider">
2747
2934
  <div class="__crossx-body">
@@ -2751,8 +2938,8 @@ button.__crossx-connect-other-block:active {
2751
2938
  <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2752
2939
  </p>
2753
2940
  <div class="__crossx-addr-pill">
2754
- ${wr}
2755
- <span class="__crossx-addr-pill-text">${Ie(s.from)}</span>
2941
+ ${Rr}
2942
+ <span class="__crossx-addr-pill-text">${Ae(s.from)}</span>
2756
2943
  </div>
2757
2944
  <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2758
2945
  </div>
@@ -2765,20 +2952,20 @@ button.__crossx-connect-other-block:active {
2765
2952
  </div>
2766
2953
  </div>
2767
2954
  </div>
2768
- `,o}function pc(s,e,r){const t=e,n=Tt(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=`
2955
+ `,o}function tl(s,e,r){const t=e,n=Dt(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=`
2769
2956
  <div class="__crossx-td-row">
2770
2957
  <span class="__crossx-td-label">${v((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
2771
2958
  <span class="__crossx-td-value">${v(o)}</span>
2772
- </div>`;for(const[u,p]of Object.entries(a)){const _=ic(p),w=nc(p)?`<span class="__crossx-addr-text">${Ie(p)}</span>
2773
- <button class="__crossx-copy-btn" data-copy="${v(String(p))}" title="Copy">${Re}</button>`:`<span>${_}</span>`;c+=`
2959
+ </div>`;for(const[d,p]of Object.entries(a)){const f=zc(p),w=qc(p)?`<span class="__crossx-addr-text">${Ae(p)}</span>
2960
+ <button class="__crossx-copy-btn" data-copy="${v(String(p))}" title="Copy">${Te}</button>`:`<span>${f}</span>`;c+=`
2774
2961
  <div class="__crossx-td-row">
2775
- <span class="__crossx-td-label">${v(u)}</span>
2962
+ <span class="__crossx-td-label">${v(d)}</span>
2776
2963
  <div class="__crossx-td-value">${w}</div>
2777
- </div>`}const l=document.createElement("div");return l.id=re,l.innerHTML=`
2964
+ </div>`}const l=document.createElement("div");return l.id=Y,l.innerHTML=`
2778
2965
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2779
2966
  <div class="__crossx-header">
2780
2967
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
2781
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2968
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2782
2969
  </div>
2783
2970
  <hr class="__crossx-divider">
2784
2971
  <div class="__crossx-body">
@@ -2788,8 +2975,8 @@ button.__crossx-connect-other-block:active {
2788
2975
  <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2789
2976
  </p>
2790
2977
  <div class="__crossx-addr-pill">
2791
- ${wr}
2792
- <span class="__crossx-addr-pill-text">${Ie(s.from)}</span>
2978
+ ${Rr}
2979
+ <span class="__crossx-addr-pill-text">${Ae(s.from)}</span>
2793
2980
  </div>
2794
2981
  <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2795
2982
  </div>
@@ -2802,12 +2989,13 @@ button.__crossx-connect-other-block:active {
2802
2989
  </div>
2803
2990
  </div>
2804
2991
  </div>
2805
- `,l}const fc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2806
- <line x1="12" y1="5" x2="12" y2="19"/>
2807
- <line x1="5" y1="12" x2="19" y2="12"/>
2808
- </svg>`,_c='<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 _n(s){return s.name||`Account ${s.index+1}`}function gc(){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">${hn}</g></svg>`}const xc=Bt().portraitBaseUrl;function wc(s,e){const r=e.replace("#","");return`${xc}/portrait/evm/${encodeURIComponent(s)}.png?size=256&bg=${encodeURIComponent(r)}`}function gn(s,e,r){const t=wc(s,r),i=gc().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${v(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 mc(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">${v((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${_c}</span>`:"";return`<button class="__crossx-wallet-item${l}" data-wallet-index="${v(String(a.index))}" data-wallet-address="${v(a.address)}">
2809
- ${gn(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(_n(a))}</span><span class="__crossx-wallet-addr">${v(nn(a.address))}</span></span>${u}
2810
- </button>`}).join(""),o=document.createElement("div");return o.id=re,o.className="__crossx-overlay--wallet-selector",o.innerHTML=`
2992
+ `,l}const rl='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12H19M12 5V19"/></svg>',sl='<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 Dn(s){return s.name||`Account ${s.index+1}`}function nl(){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">${$c}</g></svg>`}const il=wt().portraitBaseUrl;function ol(s,e){const r=e.replace("#","");return`${il}/portrait/evm/${encodeURIComponent(s)}.png?size=256&bg=${encodeURIComponent(r)}`}function Ln(s,e,r){const t=ol(s,r),i=nl().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${v(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 al(s,e,r,t,n=!0){const i=s.length===0,o=n||i?`<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2993
+ <span class="__crossx-wallet-add-icon">${rl}</span>
2994
+ <span class="__crossx-wallet-add-label">${v((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
2995
+ </button>
2996
+ <p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>`:"",a=r==null?void 0:r.toLowerCase(),c=s.map(p=>{const f=a&&p.address.toLowerCase()===a,g=f?" __crossx-wallet-item--selected":"",w=f?`<span class="__crossx-wallet-selected">${v((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${sl}</span>`:"";return`<button class="__crossx-wallet-item${g}" data-wallet-index="${v(String(p.index))}" data-wallet-address="${v(p.address)}">
2997
+ ${Ln(p.address,p.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(Dn(p))}</span><span class="__crossx-wallet-addr">${v(In(p.address))}</span></span>${w}
2998
+ </button>`}).join(""),l=i?`<p class="__crossx-wallet-empty" id="__crossx-wallet-empty">${v((t==null?void 0:t.wallet_selector_empty)??"No wallet yet. Add a wallet to continue.")}</p>`:"",d=document.createElement("div");return d.id=Y,d.className="__crossx-overlay--wallet-selector",d.innerHTML=`
2811
2999
  <div class="__crossx-card __crossx-card--wallet-selector" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2812
3000
  <div class="__crossx-header">
2813
3001
  <span class="__crossx-wallet-sheet-handle" aria-hidden="true"></span>
@@ -2815,19 +3003,15 @@ button.__crossx-connect-other-block:active {
2815
3003
  <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
2816
3004
  <p class="__crossx-subtitle--body">${v((t==null?void 0:t.wallet_selector_description)??"Please select the wallet you previously used for this game to continue.")}</p>
2817
3005
  </div>
2818
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3006
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2819
3007
  </div>
2820
3008
  <hr class="__crossx-divider">
2821
3009
  <div class="__crossx-body __crossx-wallet-selector-body">
2822
3010
  <div class="__crossx-wallet-list-section">
2823
3011
  <div class="__crossx-wallet-list" id="__crossx-wallet-list">
2824
- ${i}
3012
+ ${c}${l}
2825
3013
  </div>
2826
- <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2827
- <span class="__crossx-wallet-add-icon">${fc}</span>
2828
- <span class="__crossx-wallet-add-label">${v((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
2829
- </button>
2830
- <p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
3014
+ ${o}
2831
3015
  </div>
2832
3016
  <div class="__crossx-wallet-help-section">
2833
3017
  <div class="__crossx-mig-info">
@@ -2837,41 +3021,42 @@ button.__crossx-connect-other-block:active {
2837
3021
  </div>
2838
3022
  </div>
2839
3023
  </div>
2840
- `,o}function yc(s,e){const r=document.createElement("div");r.id=re;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Qa(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.innerHTML=oe,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 _=g=>{const m=document.createElement("span");return m.className=g,m};p.append(_("__crossx-wallet-created-shadow"),_("__crossx-wallet-created-wallet"),_("__crossx-wallet-created-coin"),_("__crossx-wallet-created-burst"),_("__crossx-wallet-created-pointer"),_("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--purple"),_("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--teal"),_("__crossx-wallet-created-dot __crossx-wallet-created-dot--one"),_("__crossx-wallet-created-dot __crossx-wallet-created-dot--two")),u.appendChild(p),l.appendChild(u);const x=document.createElement("div");x.className="__crossx-wallet-created-footer";const w=document.createElement("button");return w.className="__crossx-wallet-created-btn",w.id="__crossx-wallet-created-done",w.type="button",w.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",x.appendChild(w),t.append(n,c,l,x),r.appendChild(t),r}const bc=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
3024
+ `,d}function cl(s,e){const r=document.createElement("div");r.id=Y;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Wc(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.innerHTML=ie,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 d=document.createElement("div");d.className="__crossx-wallet-created-hero";const p=document.createElement("span");p.className="__crossx-wallet-created-illust",p.ariaHidden="true",p.innerHTML=Sc,d.appendChild(p),l.appendChild(d);const f=document.createElement("div");f.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",f.appendChild(g),t.append(n,c,l,f),r.appendChild(t),r}const ll=`<svg width="32" height="32" viewBox="4.62 5.5 30.16 30.16" fill="none" xmlns="http://www.w3.org/2000/svg">
2841
3025
  <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"/>
2842
3026
  <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"/>
2843
- </svg>`,Sc=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
3027
+ </svg>`,dl=`<svg width="32" height="32" viewBox="-2.77 -2.77 45.54 45.54" fill="none" xmlns="http://www.w3.org/2000/svg">
2844
3028
  <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"/>
2845
3029
  <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"/>
2846
3030
  <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"/>
2847
3031
  <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"/>
2848
- </svg>`;function vc(s){const e=Tr(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${ja[s]??""}</span><span class="__crossx-connect-other-wallet-name">${v(e)}</span></span>`}function Ec(s){if(s.length===0)return"";const e=n=>vc(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 Ac(s,e=[],r){const t=s,n=v(String(e[0])),i=v((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
3032
+ </svg>`;function ul(s){const e=$r(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Mc[s]??""}</span><span class="__crossx-connect-other-wallet-name">${v(e)}</span></span>`}function hl(s){if(s.length===0)return"";const e=n=>ul(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 pl(s,e=[],r){const t=s,n=v(String(e[0])),i=v((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
2849
3033
  <div class="__crossx-login-or-divider">
2850
3034
  <hr><span>${i}</span><hr>
2851
3035
  </div>
2852
3036
  <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${n}" aria-labelledby="__crossx-connect-other-heading">
2853
3037
  <span class="__crossx-connect-other-text">
2854
3038
  <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${v((r==null?void 0:r.login_selector_connect_other_wallets)??"Connect with Other Wallets")}</span>
2855
- <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${Ec(e)}</span>
3039
+ <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${hl(e)}</span>
2856
3040
  </span>
2857
- </button>`:"",a=document.createElement("div");return a.id=re,a.innerHTML=`
2858
- <div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3041
+ </button>`:"",a=document.createElement("div");return a.id=Y,a.innerHTML=`
3042
+ <div class="__crossx-card __crossx-card--migration __crossx-card--login" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2859
3043
  <div class="__crossx-header">
2860
- <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
2861
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${v((r==null?void 0:r.login_selector_title)??dt)}</p>
3044
+ <span class="__crossx-login-sheet-handle" aria-hidden="true"></span>
3045
+ <div class="__crossx-login-title-wrap" style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
3046
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${v((r==null?void 0:r.login_selector_title)??pt)}</p>
2862
3047
  <p class="__crossx-subtitle">${v((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
2863
3048
  </div>
2864
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3049
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2865
3050
  </div>
2866
3051
  <hr class="__crossx-divider">
2867
3052
  <div class="__crossx-body">
2868
3053
  <div class="__crossx-login-btn-row">
2869
3054
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
2870
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${bc}</span>
3055
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${ll}</span>
2871
3056
  <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
2872
3057
  </button>
2873
3058
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
2874
- <span class="__crossx-login-icon">${Sc}</span>
3059
+ <span class="__crossx-login-icon">${dl}</span>
2875
3060
  <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
2876
3061
  </button>
2877
3062
  </div>${o}
@@ -2880,14 +3065,14 @@ button.__crossx-connect-other-block:active {
2880
3065
  </p>
2881
3066
  </div>
2882
3067
  </div>
2883
- `,a}function Ic(s,e){const r=s,t=document.createElement("div");t.id=re;const n=v(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
3068
+ `,a}function _l(s,e){const r=s,t=document.createElement("div");t.id=Y;const n=v(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
2884
3069
  <p class="__crossx-session-account-label">${v(e.accountLabel)}</p>
2885
3070
  <p class="__crossx-session-account-email">${v(e.email)}</p>
2886
3071
  </div>`:"";return t.innerHTML=`
2887
3072
  <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
2888
3073
  <div class="__crossx-header">
2889
3074
  <p class="__crossx-title" id="__crossx-session-header-title">${v(e.title)}</p>
2890
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3075
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2891
3076
  </div>
2892
3077
  <hr class="__crossx-divider">
2893
3078
  <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
@@ -2902,7 +3087,23 @@ button.__crossx-connect-other-block:active {
2902
3087
  </div>
2903
3088
  </div>
2904
3089
  </div>
2905
- `,t}function Rc(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=re,i.innerHTML=`
3090
+ `,t}function fl(s,e){const r=document.createElement("div");r.id=Y;const t=v(e.message).replace(/\n/g,"<br>");return r.innerHTML=`
3091
+ <div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-update-title" aria-describedby="__crossx-update-msg">
3092
+ <div class="__crossx-header">
3093
+ <p class="__crossx-title" id="__crossx-update-title">${v(e.title)}</p>
3094
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3095
+ </div>
3096
+ <hr class="__crossx-divider">
3097
+ <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
3098
+ <div class="__crossx-session-hero">
3099
+ <p class="__crossx-session-hero-message" id="__crossx-update-msg">${t}</p>
3100
+ </div>
3101
+ <div class="__crossx-btn-row">
3102
+ <button class="__crossx-confirm-btn" id="__crossx-update-ok">${v(e.confirmLabel)}</button>
3103
+ </div>
3104
+ </div>
3105
+ </div>
3106
+ `,r}function gl(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=Y,i.innerHTML=`
2906
3107
  <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2907
3108
  <div class="__crossx-header">
2908
3109
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
@@ -2916,17 +3117,17 @@ button.__crossx-connect-other-block:active {
2916
3117
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
2917
3118
  </div>
2918
3119
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
2919
- <span class="__crossx-recover-icon">${un(40,"recover")}</span>
3120
+ <span class="__crossx-recover-icon">${On(40,"recover")}</span>
2920
3121
  <span class="__crossx-recover-label">Import from Social Backup</span>
2921
3122
  </button>
2922
3123
  ${n}
2923
3124
  </div>
2924
3125
  </div>
2925
- `,i}function Tc(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=re,p.innerHTML=`
3126
+ `,i}function xl(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>':"",d=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=Y,p.innerHTML=`
2926
3127
  <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2927
3128
  <div class="__crossx-header">
2928
3129
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2929
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3130
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2930
3131
  </div>
2931
3132
  <hr class="__crossx-divider">
2932
3133
  <div class="__crossx-pin-center">
@@ -2939,14 +3140,14 @@ button.__crossx-connect-other-block:active {
2939
3140
  <input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
2940
3141
  </div>
2941
3142
  <p class="__crossx-pin-hint">Enter your 4-digit PIN to recover your wallet.</p>
2942
- ${u}
3143
+ ${d}
2943
3144
  </div>
2944
3145
  </div>
2945
- `,p}function kc(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 Nc(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?kc(i):null,a=document.createElement("div");return a.id=re,a.innerHTML=`
3146
+ `,p}function wl(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 ml(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?wl(i):null,a=document.createElement("div");return a.id=Y,a.innerHTML=`
2946
3147
  <div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2947
3148
  <div class="__crossx-header">
2948
3149
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2949
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3150
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2950
3151
  </div>
2951
3152
  <hr class="__crossx-divider">
2952
3153
  <div class="__crossx-pin-center">
@@ -2962,9 +3163,9 @@ button.__crossx-connect-other-block:active {
2962
3163
  </div>
2963
3164
  </div>
2964
3165
  </div>
2965
- `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function Cc(s){const r=[s.check1,s.check2].map((t,n)=>`
3166
+ `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function yl(s){const r=[s.check1,s.check2].map((t,n)=>`
2966
3167
  <div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
2967
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Lc}</div>
3168
+ <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${El}</div>
2968
3169
  <span class="__crossx-pw-notice-item-text">${v(t)}</span>
2969
3170
  </div>
2970
3171
  `).join("");return`
@@ -2972,14 +3173,14 @@ button.__crossx-connect-other-block:active {
2972
3173
  <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
2973
3174
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
2974
3175
  <p class="__crossx-pw-subtitle">${v(s.headerSubtitle)}</p>
2975
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3176
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2976
3177
  </div>
2977
3178
  <hr class="__crossx-divider">
2978
3179
  <div class="__crossx-pw-body">
2979
3180
  <div class="__crossx-pw-fields __crossx-pw-fields--notice">
2980
3181
  <div class="__crossx-pw-notice-header">
2981
3182
  <div class="__crossx-pw-notice-title-row">
2982
- <span class="__crossx-pw-notice-icon">${Bc}</span>
3183
+ <span class="__crossx-pw-notice-icon">${Il}</span>
2983
3184
  <p class="__crossx-pw-notice-title">${v(s.noticeTitle)}</p>
2984
3185
  </div>
2985
3186
  <p class="__crossx-pw-notice-desc">${v(s.noticeDesc)}</p>
@@ -2997,45 +3198,45 @@ button.__crossx-connect-other-block:active {
2997
3198
  </button>
2998
3199
  </div>
2999
3200
  <div class="__crossx-home-indicator"></div>
3000
- `}function mr(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">${v(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${v(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${v(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">
3001
- ${wn}
3201
+ `}function Nr(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">${v(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${v(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${v(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">
3202
+ ${Mn}
3002
3203
  <span id="__crossx-pin6-lock-countdown"></span>
3003
- </p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${v(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},(g,m)=>`<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 ${m+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",_=Array.from({length:6},(g,m)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${m}" aria-label="PIN digit ${m+1}"></div>`).join(""),x=e?" --disabled":"",w=`
3204
+ </p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${v(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":"",d=Array.from({length:6},(m,x)=>`<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 ${x+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",f=Array.from({length:6},(m,x)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${x}" aria-label="PIN digit ${x+1}"></div>`).join(""),g=e?" --disabled":"",w=`
3004
3205
  <div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
3005
3206
  <div class="__crossx-pin6-numpad-row">
3006
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="1">1</button>
3007
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="2">2</button>
3008
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="3">3</button>
3207
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="1">1</button>
3208
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="2">2</button>
3209
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="3">3</button>
3009
3210
  </div>
3010
3211
  <div class="__crossx-pin6-numpad-row">
3011
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="4">4</button>
3012
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="5">5</button>
3013
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="6">6</button>
3212
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="4">4</button>
3213
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="5">5</button>
3214
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="6">6</button>
3014
3215
  </div>
3015
3216
  <div class="__crossx-pin6-numpad-row">
3016
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="7">7</button>
3017
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="8">8</button>
3018
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="9">9</button>
3217
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="7">7</button>
3218
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="8">8</button>
3219
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="9">9</button>
3019
3220
  </div>
3020
3221
  <div class="__crossx-pin6-numpad-row">
3021
3222
  <button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
3022
- <button type="button" class="__crossx-pin6-numpad-key${x}" data-key="0">0</button>
3023
- <button type="button" class="__crossx-pin6-numpad-key --delete${x}" data-key="backspace" aria-label="Delete">${Dc}</button>
3223
+ <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="0">0</button>
3224
+ <button type="button" class="__crossx-pin6-numpad-key --delete${g}" data-key="backspace" aria-label="Delete">${vl}</button>
3024
3225
  </div>
3025
3226
  </div>`;return`
3026
3227
  <div class="__crossx-header">
3027
3228
  <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
3028
3229
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
3029
3230
  ${t}
3030
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
3231
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3031
3232
  </div>
3032
3233
  <hr class="__crossx-divider">
3033
3234
  <div class="__crossx-pin6-body"${r}>
3034
3235
  ${n}
3035
3236
  <div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
3036
- ${u}
3237
+ ${d}
3037
3238
  <div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
3038
- ${_}
3239
+ ${f}
3039
3240
  </div>
3040
3241
  </div>
3041
3242
  ${i}
@@ -3044,20 +3245,21 @@ button.__crossx-connect-other-block:active {
3044
3245
  ${o}
3045
3246
  </div>
3046
3247
  ${w}
3047
- `}function xn(s,e){const r=document.createElement("div");return r.id=re,r.innerHTML=`
3248
+ `}function Bn(s,e){const r=document.createElement("div");return r.id=Y,r.innerHTML=`
3048
3249
  <div class="__crossx-card __crossx-card--pin6" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3049
3250
  ${e}
3050
3251
  </div>
3051
- `,r}function Oc(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 Pc(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 yr(s,e,r,t,n,i,o){var O,K;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"),_=()=>s.querySelector("#__crossx-pin6-lock-msg"),x=()=>s.querySelector("#__crossx-pin6-lock-countdown"),w=()=>s.querySelector(".__crossx-pin6-body"),g="●",m=(S,A)=>{S.dataset.digit=A,S.value=g},E=S=>{delete S.dataset.digit,S.value=""},I=S=>S.dataset.digit??"",N=()=>l().map(I).join(""),L=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),W=()=>{var k;const S=l(),A=L();if(A.length&&(A.forEach((R,H)=>{const V=!!(S[H]&&I(S[H]));R.classList.toggle("--filled",V),R.classList.toggle("--active",!1)}),!a&&!c)){const R=S.findIndex(V=>!I(V));(k=A[R===-1?5:R])==null||k.classList.add("--active")}},z=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(A=>A.classList.toggle("--disabled",a)),L().forEach(A=>A.classList.toggle("--locked",a)),W()},Q=S=>{a=S,l().forEach(A=>{A.disabled=S,A.classList.toggle("--locked",S)})},Y=()=>s.querySelector("#__crossx-pin6-attempt"),G=()=>{const S=p();S&&(S.textContent="")},ne=()=>o??"Your account will be locked after further failures.",D=()=>s.querySelector("#__crossx-pin6-warning"),F=S=>{var k;let A=D();if(!A){A=document.createElement("p"),A.className="__crossx-pin6-warning",A.id="__crossx-pin6-warning";const R=p();R?R.insertAdjacentElement("afterend",A):(k=w())==null||k.appendChild(A)}A.textContent=S},U=()=>{const S=D();S&&(S.textContent="")},y=(S,A)=>{var R;let k=Y();if(!k){k=document.createElement("p"),k.className="__crossx-pin6-attempt",k.id="__crossx-pin6-attempt";const H=D()??p();H?H.insertAdjacentElement("afterend",k):(R=w())==null||R.appendChild(k)}k.textContent=`${S}/${A}`},b=()=>{const S=Y();S&&(S.textContent="")},T=S=>{const A=p();A&&(A.textContent=S);const k=u();k==null||k.classList.add("--shake"),setTimeout(()=>k==null?void 0:k.classList.remove("--shake"),500),l().forEach(E),setTimeout(()=>{var R;(R=l()[0])==null||R.focus(),W()},50)},C=S=>{var V;Q(!0),l().forEach(E),z();const A=p();if(A&&(A.textContent="Too many failed attempts. Please wait."),!_()){const j=document.createElement("p");j.className="__crossx-pin6-lock-msg",j.id="__crossx-pin6-lock-msg",j.innerHTML=`${wn}<span id="__crossx-pin6-lock-countdown"></span>`;const q=p();q?q.insertAdjacentElement("afterend",j):(V=w())==null||V.appendChild(j)}const k=()=>{var X;const j=S-Date.now(),q=x();j<=0?(clearInterval(R),Q(!1),(X=_())==null||X.remove(),A&&(A.textContent=""),z(),setTimeout(()=>{var Ue;return(Ue=l()[0])==null?void 0:Ue.focus()},50)):q&&(q.textContent=` ${Pc(j)}`)},R=setInterval(k,1e3);k();const H=new MutationObserver(()=>{document.contains(s)||(clearInterval(R),H.disconnect())});H.observe(document.body,{childList:!0,subtree:!1})},$=async()=>{if(a||c)return;const S=N();if(S.length===6){c=!0,l().forEach(A=>{A.disabled=!0});try{if(n){const A=await n(S);A.ok?e(S):A.lockExpiresAt?(b(),C(A.lockExpiresAt)):(T(A.error??"Incorrect PIN. Please try again."),A.attemptCount!=null&&A.maxAttempts!=null?(F(ne()),y(A.attemptCount,A.maxAttempts)):(U(),b()))}else e(S)}catch(A){t&&t(A)}finally{c=!1,a||l().forEach(A=>{A.disabled=!1}),W()}}};i&&i>Date.now()?C(i):setTimeout(()=>{var S;return(S=l()[0])==null?void 0:S.focus()},100);const B=()=>{if(a||c)return;const S=l(),A=S.find(k=>!I(k))??S[S.length-1];A==null||A.focus()};(O=u())==null||O.addEventListener("click",S=>{S.target.classList.contains("__crossx-pin6-box")||B()}),(K=w())==null||K.addEventListener("click",S=>{const A=S.target;A.classList.contains("__crossx-pin6-box")||A.closest("button")||B()}),l().forEach((S,A)=>{S.addEventListener("input",()=>{var R;const k=S.value.replace(/\D/g,"").slice(-1);k?m(S,k):E(S),G(),k&&A<5&&((R=l()[A+1])==null||R.focus()),W(),N().length===6&&setTimeout($,80)}),S.addEventListener("keydown",k=>{var R,H;if(k.key==="Backspace"){if(k.preventDefault(),I(S))E(S);else if(A>0){const V=l()[A-1];E(V),V.focus()}W()}else k.key==="ArrowLeft"&&A>0?(k.preventDefault(),(R=l()[A-1])==null||R.focus()):k.key==="ArrowRight"&&A<5?(k.preventDefault(),(H=l()[A+1])==null||H.focus()):k.key==="Escape"&&r()}),S.addEventListener("paste",k=>{var V,j;k.preventDefault();const R=(((V=k.clipboardData)==null?void 0:V.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!R)return;const H=l();R.split("").forEach((q,X)=>{H[X]&&m(H[X],q)}),(j=H[Math.min(R.length-1,5)])==null||j.focus(),G(),W(),N().length===6&&setTimeout($,80)}),S.addEventListener("focus",()=>S.select())});const M=s.querySelector("#__crossx-pin6-numpad");if(M){let S=null;const A=()=>{S&&(S.classList.remove("--pressed"),S=null)};M.addEventListener("pointerdown",R=>{const H=R.target.closest(".__crossx-pin6-numpad-key");!H||a||c||(A(),S=H,H.classList.add("--pressed"),H.setPointerCapture(R.pointerId))});const k=R=>{const H=R.dataset.key;if(!H)return;if(H==="backspace"){const X=[...l()].reverse().find(Ue=>I(Ue));X&&(E(X),G()),W();return}if(!/^\d$/.test(H))return;const j=l().find(q=>!I(q));j&&(m(j,H),G(),W(),N().length===6&&setTimeout($,80))};M.addEventListener("pointerup",R=>{if(!S)return;const H=S;A();const V=H.getBoundingClientRect();R.clientX>=V.left&&R.clientX<=V.right&&R.clientY>=V.top&&R.clientY<=V.bottom&&!a&&!c&&k(H)}),M.addEventListener("pointercancel",A),M.addEventListener("pointerleave",A,!0),W(),i&&i>Date.now()&&z()}}const Dc=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3252
+ `,r}function bl(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 Sl(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 Cr(s,e,r,t,n,i,o){var k,V;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),d=()=>s.querySelector("#__crossx-pin6-boxes"),p=()=>s.querySelector("#__crossx-pin6-error"),f=()=>s.querySelector("#__crossx-pin6-lock-msg"),g=()=>s.querySelector("#__crossx-pin6-lock-countdown"),w=()=>s.querySelector(".__crossx-pin6-body"),m="●",x=(E,A)=>{E.dataset.digit=A,E.value=m},S=E=>{delete E.dataset.digit,E.value=""},I=E=>E.dataset.digit??"",U=()=>l().map(I).join(""),C=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),L=()=>{var N;const E=l(),A=C();if(A.length&&(A.forEach((T,K)=>{const J=!!(E[K]&&I(E[K]));T.classList.toggle("--filled",J),T.classList.toggle("--active",!1)}),!a&&!c)){const T=E.findIndex(J=>!I(J));(N=A[T===-1?5:T])==null||N.classList.add("--active")}},H=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(A=>A.classList.toggle("--disabled",a)),C().forEach(A=>A.classList.toggle("--locked",a)),L()},G=E=>{a=E,l().forEach(A=>{A.disabled=E,A.classList.toggle("--locked",E)})},q=()=>s.querySelector("#__crossx-pin6-attempt"),z=()=>{const E=p();E&&(E.textContent="")},ne=()=>o??"Your account will be locked after further failures.",D=()=>s.querySelector("#__crossx-pin6-warning"),F=E=>{var N;let A=D();if(!A){A=document.createElement("p"),A.className="__crossx-pin6-warning",A.id="__crossx-pin6-warning";const T=p();T?T.insertAdjacentElement("afterend",A):(N=w())==null||N.appendChild(A)}A.textContent=E},W=()=>{const E=D();E&&(E.textContent="")},y=(E,A)=>{var T;let N=q();if(!N){N=document.createElement("p"),N.className="__crossx-pin6-attempt",N.id="__crossx-pin6-attempt";const K=D()??p();K?K.insertAdjacentElement("afterend",N):(T=w())==null||T.appendChild(N)}N.textContent=`${E}/${A}`},b=()=>{const E=q();E&&(E.textContent="")},R=E=>{const A=p();A&&(A.textContent=E);const N=d();N==null||N.classList.add("--shake"),setTimeout(()=>N==null?void 0:N.classList.remove("--shake"),500),l().forEach(S),setTimeout(()=>{var T;(T=l()[0])==null||T.focus(),L()},50)},O=E=>{var J;G(!0),l().forEach(S),H();const A=p();if(A&&(A.textContent="Too many failed attempts. Please wait."),!f()){const Z=document.createElement("p");Z.className="__crossx-pin6-lock-msg",Z.id="__crossx-pin6-lock-msg",Z.innerHTML=`${Mn}<span id="__crossx-pin6-lock-countdown"></span>`;const j=p();j?j.insertAdjacentElement("afterend",Z):(J=w())==null||J.appendChild(Z)}const N=()=>{var Q;const Z=E-Date.now(),j=g();Z<=0?(clearInterval(T),G(!1),(Q=f())==null||Q.remove(),A&&(A.textContent=""),H(),setTimeout(()=>{var Fe;return(Fe=l()[0])==null?void 0:Fe.focus()},50)):j&&(j.textContent=` ${Sl(Z)}`)},T=setInterval(N,1e3);N();const K=new MutationObserver(()=>{document.contains(s)||(clearInterval(T),K.disconnect())});K.observe(document.body,{childList:!0,subtree:!1})},$=async()=>{if(a||c)return;const E=U();if(E.length===6){c=!0,l().forEach(A=>{A.disabled=!0});try{if(n){const A=await n(E);A.ok?e(E):A.lockExpiresAt?(b(),O(A.lockExpiresAt)):(R(A.error??"Incorrect PIN. Please try again."),A.attemptCount!=null&&A.maxAttempts!=null?(F(ne()),y(A.attemptCount,A.maxAttempts)):(W(),b()))}else e(E)}catch(A){t&&t(A)}finally{c=!1,a||l().forEach(A=>{A.disabled=!1}),L()}}};i&&i>Date.now()?O(i):setTimeout(()=>{var E;return(E=l()[0])==null?void 0:E.focus()},100);const B=()=>{if(a||c)return;const E=l(),A=E.find(N=>!I(N))??E[E.length-1];A==null||A.focus()};(k=d())==null||k.addEventListener("click",E=>{E.target.classList.contains("__crossx-pin6-box")||B()}),(V=w())==null||V.addEventListener("click",E=>{const A=E.target;A.classList.contains("__crossx-pin6-box")||A.closest("button")||B()}),l().forEach((E,A)=>{E.addEventListener("input",()=>{var T;const N=E.value.replace(/\D/g,"").slice(-1);N?x(E,N):S(E),z(),N&&A<5&&((T=l()[A+1])==null||T.focus()),L(),U().length===6&&setTimeout($,80)}),E.addEventListener("keydown",N=>{var T,K;if(N.key==="Backspace"){if(N.preventDefault(),I(E))S(E);else if(A>0){const J=l()[A-1];S(J),J.focus()}L()}else N.key==="ArrowLeft"&&A>0?(N.preventDefault(),(T=l()[A-1])==null||T.focus()):N.key==="ArrowRight"&&A<5?(N.preventDefault(),(K=l()[A+1])==null||K.focus()):N.key==="Escape"&&r()}),E.addEventListener("paste",N=>{var J,Z;N.preventDefault();const T=(((J=N.clipboardData)==null?void 0:J.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!T)return;const K=l();T.split("").forEach((j,Q)=>{K[Q]&&x(K[Q],j)}),(Z=K[Math.min(T.length-1,5)])==null||Z.focus(),z(),L(),U().length===6&&setTimeout($,80)}),E.addEventListener("focus",()=>E.select())});const M=s.querySelector("#__crossx-pin6-numpad");if(M){let E=null;const A=()=>{E&&(E.classList.remove("--pressed"),E=null)};M.addEventListener("pointerdown",T=>{const K=T.target.closest(".__crossx-pin6-numpad-key");!K||a||c||(A(),E=K,K.classList.add("--pressed"),K.setPointerCapture(T.pointerId))});const N=T=>{const K=T.dataset.key;if(!K)return;if(K==="backspace"){const Q=[...l()].reverse().find(Fe=>I(Fe));Q&&(S(Q),z()),L();return}if(!/^\d$/.test(K))return;const Z=l().find(j=>!I(j));Z&&(x(Z,K),z(),L(),U().length===6&&setTimeout($,80))};M.addEventListener("pointerup",T=>{if(!E)return;const K=E;A();const J=K.getBoundingClientRect();T.clientX>=J.left&&T.clientX<=J.right&&T.clientY>=J.top&&T.clientY<=J.bottom&&!a&&!c&&N(K)}),M.addEventListener("pointercancel",A),M.addEventListener("pointerleave",A,!0),L(),i&&i>Date.now()&&H()}}const vl=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3052
3253
  <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"/>
3053
3254
  <line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3054
3255
  <line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3055
- </svg>`,wn=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3256
+ </svg>`,Mn=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3056
3257
  <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"/>
3057
- </svg>`,Lc=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3258
+ </svg>`,El=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3058
3259
  <path d="M1 4.5L4 7.5L10 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
3059
- </svg>`,Bc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3060
- <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"/>
3061
- </svg>`;function Mc(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[x]&&(t[x].value=_)});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 $c{constructor(e="light",r,t=Ot,n){this.theme=e,this.overrides=r,this.tokens=sn(e,r),this.displayDecimals=t,this.pinKeyboard=n,Ga()}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=sn(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((n,i)=>{var I;de();const o=[...e],a=mc(o,this.tokens,t,this.messages),c=$e();ue(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())};let p=null;const _=N=>{u(),n(N)},x=()=>{u(),p?i(p):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(N=>{N.addEventListener("click",()=>{const L=N.dataset.walletAddress??"",W=parseInt(N.dataset.walletIndex??"0",10),z=o.find(Q=>Q.index===W);_({address:L,index:W,name:z==null?void 0:z.name})})})})();const g=a.querySelector("#__crossx-add-wallet-error"),m=a.querySelector("#__crossx-add-wallet-btn");m&&m.addEventListener("click",async()=>{m.disabled=!0,g&&(g.hidden=!0,g.textContent="");try{const N=await r();o.push(N);const L=a.querySelector("#__crossx-wallet-list");if(L){const W=document.createElement("button");W.className="__crossx-wallet-item",W.dataset.walletIndex=String(N.index),W.dataset.walletAddress=N.address,W.innerHTML=`${gn(N.address,N.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(_n(N))}</span><span class="__crossx-wallet-addr">${v(nn(N.address))}</span></span>`,W.addEventListener("click",()=>_(N)),L.appendChild(W);try{W.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}m.disabled=!1}catch(N){const L=N instanceof f&&N.code===h.ADDRESS_LIMIT_EXCEEDED,W=this.resolveAddWalletErrorMessage(N);g&&(g.textContent=W,g.hidden=!1),L?(m.disabled=!0,m.setAttribute("aria-disabled","true")):m.disabled=!1,p=N}}),(I=a.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",x),a.addEventListener("click",N=>{N.target===a&&x()});const E=N=>{N.key==="Escape"&&(document.removeEventListener("keydown",E),x())};document.addEventListener("keydown",E)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,c;de();const r=yc(this.tokens,this.messages),t=$e();ue(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:lt;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(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var _,x,w,g;de();const i=Ac(this.tokens,r,this.messages),o=$e();ue(i);const a=()=>{i.remove(),o()},c=m=>{a(),n({type:"oauth",provider:m})},l=m=>{a(),n({type:"external",walletId:m})},u=()=>{a(),n(null)};(_=i.querySelector("#__crossx-apple-btn"))==null||_.addEventListener("click",()=>c("apple")),(x=i.querySelector("#__crossx-google-btn"))==null||x.addEventListener("click",()=>c("google")),(w=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||w.addEventListener("click",m=>{const I=m.currentTarget.dataset.walletId??"";I&&l(I)}),(g=i.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",u),i.addEventListener("click",m=>{m.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(m=>{m.addEventListener("click",E=>E.stopPropagation())});const p=m=>{m.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(r=>{var u,p,_;de();const t=this.messages,n=Ic(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=$e();ue(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),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;de();const n=Rc(this.tokens,r);ue(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",_=>{_.target===n&&u()});const p=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(r=>{de();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=xn(this.tokens,Cc(n)),c=$e();ue(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},p=I=>{u(),r(I)},_=()=>{u(),r(null)},x=a.querySelector(".__crossx-card"),w={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."},g=I=>{var N;x.innerHTML=mr({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(x),(N=x.querySelector("#__crossx-close-btn"))==null||N.addEventListener("click",_),yr(x,L=>{L===I?p(I):m(i.mismatchError)},_)},m=I=>{var N;x.innerHTML=mr({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:I}),this.applyPinKeyboardMode(x),(N=x.querySelector("#__crossx-close-btn"))==null||N.addEventListener("click",_),yr(x,L=>{const W=Oc(L,w);W?m(W):g(L)},_)};(()=>{var ne;const I=Array.from(x.querySelectorAll(".__crossx-pw-notice-item")),N=x.querySelector("#__crossx-pin-notice-next"),L=new Set;N.removeAttribute("disabled");const W=N.dataset.nextLabel??"Next",z=N.dataset.submitLabel??"I Understand",Q=()=>{const D=L.size===I.length;N.classList.toggle("--disabled",!D),N.textContent=z||W},Y=(D,F)=>{if(L.has(F))return;const U=D.querySelector(`#__crossx-notice-check-${F}`);L.add(F),U.classList.add("--checked"),D.setAttribute("aria-checked","true"),Q()},G=(D,F)=>{if(!L.has(F))return;const U=D.querySelector(`#__crossx-notice-check-${F}`);L.delete(F),U.classList.remove("--checked"),D.setAttribute("aria-checked","false"),Q()};I.forEach(D=>{const F=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{L.has(F)?G(D,F):Y(D,F)}),D.addEventListener("keydown",U=>{(U.key===" "||U.key==="Enter")&&(U.preventDefault(),L.has(F)?G(D,F):Y(D,F))})}),N.addEventListener("click",()=>{if(L.size===I.length){m(e==null?void 0:e.errorMessage);return}const D=I.find(U=>{const y=parseInt(U.dataset.checkIndex??"0",10);return!L.has(y)});if(!D)return;const F=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),Y(D,F)},400)}),(ne=x.querySelector("#__crossx-close-btn"))==null||ne.addEventListener("click",_)})(),a.addEventListener("click",I=>{I.target===a&&_()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var E;de();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=xn(this.tokens,mr({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=$e();ue(l);let p=!1;const _=()=>{p||(p=!0,l.remove(),u())},x=I=>{_(),r(I)},w=()=>{_(),r(null)},g=I=>{_(),t(I)},m=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(m),(E=m.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",w),yr(m,x,w,g,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",I=>{I.target===l&&w()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;de();const t=Tc(this.tokens,e);ue(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),Mc(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;de();const{overlay:n,startCountdown:i}=Nc(this.tokens,e,r);ue(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;de();const t=lc(e,this.tokens,this.messages);ue(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 _;u.stopPropagation();const p=l.dataset.copy;p&&((_=navigator.clipboard)==null||_.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{de();const n=dc(e,this.tokens,this.messages);ue(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,p;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(uc(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,u,p;de();let t;e.type==="sign-message"?t=hc(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=pc(e,this.tokens,this.messages):e.type==="sign"?t=ec(e,this.tokens,this.displayDecimals,this.messages):t=sc(e,this.tokens,this.displayDecimals,this.messages);const n=$e();ue(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(_=>{_.addEventListener("click",x=>{var g;x.stopPropagation();const w=_.dataset.copy;w&&((g=navigator.clipboard)==null||g.writeText(w).catch(()=>{}))})}),Ha(t),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Fc{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 mn{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 yn(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3260
+ </svg>`,Il=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3261
+ <circle cx="12" cy="12" r="10" fill="currentColor"/>
3262
+ <path d="M11.0625 13.3564H12.9375V7.51895H11.0625V13.3564ZM11.0625 16.4814H12.9375V14.6064H11.0625V16.4814Z" fill="#FFFFFF"/>
3263
+ </svg>`;function Al(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(d=>d.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((f,g)=>{t[g]&&(t[g].value=f)});const d=Math.min(l.length,3);t[d].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 Tl{constructor(e="light",r,t=$t,n){this.theme=e,this.overrides=r,this.tokens=En(e,r),this.displayDecimals=t,this.pinKeyboard=n,Oc()}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=En(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t,n){return new Promise((i,o)=>{var U;le();const a=[...e],c=al(a,this.tokens,t,this.messages,(n==null?void 0:n.showAddWallet)!==!1),l=Le();de(c);let d=!1;const p=()=>{d||(d=!0,c.remove(),l())};let f=null;const g=C=>{p(),i(C)},w=()=>{p(),f?o(f):i(null)};(()=>{c.querySelectorAll(".__crossx-wallet-item").forEach(C=>{C.addEventListener("click",()=>{const L=C.dataset.walletAddress??"",H=parseInt(C.dataset.walletIndex??"0",10),G=a.find(q=>q.index===H);g({address:L,index:H,name:G==null?void 0:G.name})})})})();const x=c.querySelector("#__crossx-add-wallet-error"),S=c.querySelector("#__crossx-add-wallet-btn");S&&S.addEventListener("click",async()=>{var C;S.disabled=!0,x&&(x.hidden=!0,x.textContent="");try{const L=await r();a.push(L),(C=c.querySelector("#__crossx-wallet-empty"))==null||C.remove();const H=c.querySelector("#__crossx-wallet-list");if(H){const G=document.createElement("button");G.className="__crossx-wallet-item",G.dataset.walletIndex=String(L.index),G.dataset.walletAddress=L.address,G.innerHTML=`${Ln(L.address,L.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(Dn(L))}</span><span class="__crossx-wallet-addr">${v(In(L.address))}</span></span>`,G.addEventListener("click",()=>g(L)),H.appendChild(G);try{G.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}if((n==null?void 0:n.showAddWallet)===!1){S.remove(),x==null||x.remove();return}S.disabled=!1}catch(L){const H=L instanceof _&&L.code===h.ADDRESS_LIMIT_EXCEEDED,G=this.resolveAddWalletErrorMessage(L);x&&(x.textContent=G,x.hidden=!1),H?(S.disabled=!0,S.setAttribute("aria-disabled","true")):S.disabled=!1,f=L}}),(U=c.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",w),c.addEventListener("click",C=>{C.target===c&&w()});const I=C=>{C.key==="Escape"&&(document.removeEventListener("keydown",I),w())};document.addEventListener("keydown",I)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,c;le();const r=cl(this.tokens,this.messages),t=Le();de(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 _&&e.code===h.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:dt;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(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var f,g,w,m;le();const i=pl(this.tokens,r,this.messages),o=Le();de(i);const a=()=>{i.remove(),o()},c=x=>{a(),n({type:"oauth",provider:x})},l=x=>{a(),n({type:"external",walletId:x})},d=()=>{a(),n(null)};(f=i.querySelector("#__crossx-apple-btn"))==null||f.addEventListener("click",()=>c("apple")),(g=i.querySelector("#__crossx-google-btn"))==null||g.addEventListener("click",()=>c("google")),(w=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||w.addEventListener("click",x=>{const I=x.currentTarget.dataset.walletId??"";I&&l(I)}),(m=i.querySelector("#__crossx-close-btn"))==null||m.addEventListener("click",d),i.addEventListener("click",x=>{x.target===i&&d()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(x=>{x.addEventListener("click",S=>S.stopPropagation())});const p=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)})}showUpdateRequired(e){return new Promise(r=>{var l,d;le();const t=this.messages,n=fl(this.tokens,{title:(e==null?void 0:e.title)??(t==null?void 0:t.update_required_title)??"Update required",message:(e==null?void 0:e.message)??(t==null?void 0:t.update_required_message)??"This service is using a wallet version that is no longer supported. Please try again after the service is updated.",confirmLabel:(t==null?void 0:t.update_required_confirm_button)??"OK"}),i=Le();de(n);let o=!1;const a=()=>{o||(o=!0,document.removeEventListener("keydown",c),n.remove(),i(),r())},c=p=>{p.key==="Escape"&&a()};document.addEventListener("keydown",c),(l=n.querySelector("#__crossx-update-ok"))==null||l.addEventListener("click",a),(d=n.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",a)})}showSessionAlert(e){return new Promise(r=>{var d,p,f;le();const t=this.messages,n=_l(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=Le();de(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(d=n.querySelector("#__crossx-session-signout"))==null||d.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;le();const n=gl(this.tokens,r);de(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const d=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",d),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",d),n.addEventListener("click",f=>{f.target===n&&d()});const p=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(r=>{le();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=Bn(this.tokens,yl(n)),c=Le();de(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())},p=I=>{d(),r(I)},f=()=>{d(),r(null)},g=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},m=I=>{var U;g.innerHTML=Nr({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(g),(U=g.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",f),Cr(g,C=>{C===I?p(I):x(i.mismatchError)},f)},x=I=>{var U;g.innerHTML=Nr({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:I}),this.applyPinKeyboardMode(g),(U=g.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",f),Cr(g,C=>{const L=bl(C,w);L?x(L):m(C)},f)};(()=>{var ne;const I=Array.from(g.querySelectorAll(".__crossx-pw-notice-item")),U=g.querySelector("#__crossx-pin-notice-next"),C=new Set;U.removeAttribute("disabled");const L=U.dataset.nextLabel??"Next",H=U.dataset.submitLabel??"I Understand",G=()=>{const D=C.size===I.length;U.classList.toggle("--disabled",!D),U.textContent=H||L},q=(D,F)=>{if(C.has(F))return;const W=D.querySelector(`#__crossx-notice-check-${F}`);C.add(F),W.classList.add("--checked"),D.setAttribute("aria-checked","true"),G()},z=(D,F)=>{if(!C.has(F))return;const W=D.querySelector(`#__crossx-notice-check-${F}`);C.delete(F),W.classList.remove("--checked"),D.setAttribute("aria-checked","false"),G()};I.forEach(D=>{const F=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{C.has(F)?z(D,F):q(D,F)}),D.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),C.has(F)?z(D,F):q(D,F))})}),U.addEventListener("click",()=>{if(C.size===I.length){x(e==null?void 0:e.errorMessage);return}const D=I.find(W=>{const y=parseInt(W.dataset.checkIndex??"0",10);return!C.has(y)});if(!D)return;const F=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),q(D,F)},400)}),(ne=g.querySelector("#__crossx-close-btn"))==null||ne.addEventListener("click",f)})(),a.addEventListener("click",I=>{I.target===a&&f()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var S;le();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=Bn(this.tokens,Nr({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})),d=Le();de(l);let p=!1;const f=()=>{p||(p=!0,l.remove(),d())},g=I=>{f(),r(I)},w=()=>{f(),r(null)},m=I=>{f(),t(I)},x=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(x),(S=x.querySelector("#__crossx-close-btn"))==null||S.addEventListener("click",w),Cr(x,g,w,m,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",I=>{I.target===l&&w()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;le();const t=xl(this.tokens,e);de(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),Al(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;le();const{overlay:n,startCountdown:i}=ml(this.tokens,e,r);de(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;le();const t=Xc(e,this.tokens,this.messages);de(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",d=>{var f;d.stopPropagation();const p=l.dataset.copy;p&&((f=navigator.clipboard)==null||f.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=>{le();const n=Zc(e,this.tokens,this.messages);de(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var d,p;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",f=>{f.target===n&&a()});const l=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(Qc(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,d,p;le();let t;e.type==="sign-message"?t=el(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=tl(e,this.tokens,this.messages):e.type==="sign"?t=Hc(e,this.tokens,this.displayDecimals,this.messages):t=Vc(e,this.tokens,this.displayDecimals,this.messages);const n=Le();de(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),(d=t.querySelector("#__crossx-cancel-btn"))==null||d.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",g=>{var m;g.stopPropagation();const w=f.dataset.copy;w&&((m=navigator.clipboard)==null||m.writeText(w).catch(()=>{}))})}),Nc(t),t.addEventListener("click",f=>{f.target===t&&a()});const c=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Rl{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 _(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,n){const i=this.getBridge();if(this.shouldDelegateToBridge()&&(i!=null&&i.showWalletSelector))try{const o=await i.showWalletSelector({requiredAddress:t}),a=e.find(c=>c.address.toLowerCase()===o.address.toLowerCase());return{address:o.address,index:(a==null?void 0:a.index)??o.index,name:a==null?void 0:a.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t,n)}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)}showUpdateRequired(e){return this.browserConfirmation.showUpdateRequired(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 $n{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}}const Nl=new WeakMap;function Cl(s,e){Nl.set(s,e)}function Un(s){return Ol(s)}function Ol(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3062
3264
  Set the projectId field in SDKConfig when calling createCROSSxSDK().
3063
- Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=Ke.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,legacyOauthServiceUrl:r.legacyOauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&Fr.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Fr(s.projectId):new gi,a=new ua,c=new va,l=new Be,u=new mn,p=new Lt,_=new fa(n,c);let x;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),x=new La(o,p)):(d.log("[CROSSx] Remote Wallet Provider 사용"),x=new Me(n,o,c,u,p,_));let w=null;const g=()=>{var Y;return((Y=w==null?void 0:w.isAuthenticatedViaRNBridge)==null?void 0:Y.call(w))??!1},m=()=>{var Y;return(Y=w==null?void 0:w.assertRNBridgeSessionActive)==null?void 0:Y.call(w)},E=Y=>{var G;(G=w==null?void 0:w.clearRNBridgeDelegation)==null||G.call(w,Y)};x=new Ma(x,()=>{var Y;return(Y=w==null?void 0:w.getRNBridge)==null?void 0:Y.call(w)},g,m,()=>s.appName,E);const I=new ct(n,c),N=new $c(s.theme??"light",s.themeTokens,s.displayDecimals,s.pinKeyboard),L=new Fc(N,()=>{var Y;return(Y=w==null?void 0:w.getRNBridge)==null?void 0:Y.call(w)},()=>typeof window<"u"?window.location.origin:"http://localhost",g),W=e!=null&&e.wrapConfirmation?e.wrapConfirmation(L):L,z=new et(t,n,o,a,c,l,x,u,W,I,p,_);w=z;const Q=z.signInUseCase;return Q&&typeof Q.setFreshTokenCallback=="function"&&Q.setFreshTokenCallback(()=>z.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=z),z}const Uc=yn;function Wc(s){const e=Hc(s),r=Kc(e),t=JSON.parse(r);Vc(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 Hc(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 Kc(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=Gc(s);return decodeURIComponent(e)}function Gc(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 Vc(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 필드가 없습니다")}return J.CONNECT_OTHER_WALLET_DISPLAY_ORDER=Rr,J.CROSSxError=f,J.CROSSxEthereumProvider=Pt,J.CROSSxSDK=et,J.ChainId=Bn,J.ConnectOtherWalletItem=We,J.ErrorCode=h,J.MNEMONIC_ADDRESS_LIMIT=lt,J.ONEpocketError=f,J.ONEpocketEthereumProvider=Pt,J.ONEpocketSDK=et,J.PinMemoryStore=Lt,J.TokenMemoryStore=mn,J.WALLET_BRAND_NAME=dt,J.createCROSSxSDK=yn,J.createONEpocketSDK=Uc,J.getConnectOtherWalletLabel=Tr,J.getWalletBrowserInfo=ot,J.isWalletInAppBrowser=ka,J.parseOAuthDeeplink=Wc,J.waitForWalletBrowser=Na,Object.defineProperty(J,Symbol.toStringTag,{value:"Module"}),J})({});
3265
+ Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=Ke.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,legacyOauthServiceUrl:r.legacyOauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&ns.isAvailable();!i&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new ns(s.projectId):new Xi,a=new qa;let c=null;const l=new oc(new nc,{version:ut,sendVersionHeader:Yn,getGatewayBaseUrls:()=>[n.gatewayUrl],onDeprecation:q=>c==null?void 0:c.handleSdkVersionDeprecation(q),onUnsupported:q=>c==null?void 0:c.handleSdkVersionUnsupported(q)}),d=new $e,p=new $n,f=new Wt,g=new ja(n,l);let w;s.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),w=new mc(o,f)):(u.log("[CROSSx] Remote Wallet Provider 사용"),w=new Ue(n,o,l,p,f,g));const m=()=>{var q;return((q=c==null?void 0:c.isAuthenticatedViaRNBridge)==null?void 0:q.call(c))??!1},x=()=>{var q;return(q=c==null?void 0:c.assertRNBridgeSessionActive)==null?void 0:q.call(c)},S=q=>{var z;(z=c==null?void 0:c.clearRNBridgeDelegation)==null||z.call(c,q)};w=new bc(w,()=>{var q;return(q=c==null?void 0:c.getRNBridge)==null?void 0:q.call(c)},m,x,()=>s.appName,S);const I=new lt(n,l),U=new Tl(s.theme??"light",s.themeTokens,s.displayDecimals,s.pinKeyboard),L=new Rl(U,()=>{var q;return(q=c==null?void 0:c.getRNBridge)==null?void 0:q.call(c)},()=>typeof window<"u"?window.location.origin:"http://localhost",m),H=new tt(t,n,o,a,l,d,w,p,L,I,f,g,new vi);c=H,Cl(H,{transport:l,storage:o,walletProvider:w,confirmation:L,tokenStore:p,pinStore:f,adapterConfig:n,pinEncryptor:g});const G=H.signInUseCase;return G&&typeof G.setFreshTokenCallback=="function"&&G.setFreshTokenCallback(()=>H.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=H),H}const kl=Un;function Pl(s){const e=Dl(s),r=Ll(e),t=JSON.parse(r);Ml(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 Dl(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 Ll(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=Bl(s);return decodeURIComponent(e)}function Bl(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 Ml(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 필드가 없습니다")}return X.CONNECT_OTHER_WALLET_DISPLAY_ORDER=Mr,X.CROSSxError=_,X.CROSSxEthereumProvider=Ut,X.CROSSxSDK=tt,X.ChainId=si,X.ConnectOtherWalletItem=We,X.ErrorCode=h,X.MNEMONIC_ADDRESS_LIMIT=dt,X.ONEpocketError=_,X.ONEpocketEthereumProvider=Ut,X.ONEpocketSDK=tt,X.PinMemoryStore=Wt,X.TokenMemoryStore=$n,X.WALLET_BRAND_NAME=pt,X.createCROSSxSDK=Un,X.createONEpocketSDK=kl,X.getConnectOtherWalletLabel=$r,X.getWalletBrowserInfo=at,X.isWalletInAppBrowser=pc,X.parseOAuthDeeplink=Pl,X.waitForWalletBrowser=_c,Object.defineProperty(X,Symbol.toStringTag,{value:"Module"}),X})({});