@nexus-cross/crossx-sdk-core 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ce=require("jose"),Bt=require("@noble/curves/secp256k1.js"),Qe=require("@noble/hashes/sha3.js"),Ut=require("@noble/hashes/utils.js");var d=(i=>(i.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",i.AUTH_FAILED="AUTH_FAILED",i.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",i.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",i.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",i.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",i.SESSION_EXPIRED="SESSION_EXPIRED",i.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",i.WALLET_NOT_FOUND="WALLET_NOT_FOUND",i.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",i.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",i.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",i.SIGN_FAILED="SIGN_FAILED",i.SIGN_REJECTED="SIGN_REJECTED",i.TX_FAILED="TX_FAILED",i.TX_REJECTED="TX_REJECTED",i.BROADCAST_FAILED="BROADCAST_FAILED",i.USER_REJECTED="USER_REJECTED",i.TX_INVALID_PARAMS="TX_INVALID_PARAMS",i.NETWORK_ERROR="NETWORK_ERROR",i.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",i.INVALID_CHAIN="INVALID_CHAIN",i.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",i.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",i.NOT_IMPLEMENTED="NOT_IMPLEMENTED",i.SIGNATURE_FAILED="SIGNATURE_FAILED",i.TRANSACTION_FAILED="TRANSACTION_FAILED",i.PREPARE_FAILED="PREPARE_FAILED",i.PREPARE_EXPIRED="PREPARE_EXPIRED",i.PREPARE_MISMATCH="PREPARE_MISMATCH",i.MIGRATION_FAILED="MIGRATION_FAILED",i.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",i.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",i.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",i.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",i.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",i.PROJECT_ID_MISSING="PROJECT_ID_MISSING",i.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",i.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",i.INVALID_APP_TYPE="INVALID_APP_TYPE",i.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",i.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",i.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",i.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",i.PIN_NOT_SET="PIN_NOT_SET",i.PIN_WRONG="PIN_WRONG",i.PIN_INVALID="PIN_INVALID",i.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",i.PIN_CANCELLED="PIN_CANCELLED",i.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",i.PIN_LOCKED="PIN_LOCKED",i.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",i.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",i.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",i.HMAC_REQUIRED="HMAC_REQUIRED",i.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",i.WITHDRAW_FAILED="WITHDRAW_FAILED",i.USER_NOT_FOUND="USER_NOT_FOUND",i.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",i.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",i.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",i.INVALID_CONFIG="INVALID_CONFIG",i.UNKNOWN_ERROR="UNKNOWN_ERROR",i))(d||{});class u extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,u.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Wt=2e3,et=6e4,Ht=1e3,Gt=1e4,Kt="0x77359400",tt="0x3B9ACA00",rt=130,Ve=6,st=18,it=3e4,Vt=5*60*1e3,qt=30*1e3,Ee=100,zt=5*60*1e3,nt=60*1e3,jt=5*60*1e3,Yt="crossx-sdk-js/2.4.0",Te="ONEpocket";var pe=(i=>(i.MetaMask="io.metamask",i.Binance="com.binance.wallet",i.CROSSx="crossx",i))(pe||{});const Xt={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:Te},mt=["crossx","io.metamask","com.binance.wallet"];function yt(i){return Xt[i]??i}function Jt(i){return Array.isArray(i.connectOtherWallets)&&i.connectOtherWallets.length>0?[...i.connectOtherWallets]:i.showConnectOtherWallets===!0?[...mt]:[]}function bt(i){const e=i instanceof Error?i.message:String(i);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const Re={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}},Zt=Object.fromEntries(Object.entries(Re).map(([i,e])=>[i,e.caipId])),Qt=new Map(Object.values(Re).map(i=>[i.caipId,i]));new Map(Object.values(Re).map(i=>[i.chainId,i]));const er={symbol:"",decimals:18};function Oe(i){var e;return((e=Qt.get(i))==null?void 0:e.nativeCurrency)??er}class St{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 u(d.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new u(d.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(s=>s(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let Z=null;function ot(i){Z=i}const c={info(...i){if(Z){Z.log(...i);return}console.log(...i)},log(...i){if(Z){Z.log(...i);return}},warn(...i){if(Z){Z.warn(...i);return}},error(...i){if(Z){Z.error(...i);return}}},tr={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:`소셜 계정에 연결된 지갑을 발견했습니다.
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Oe=require("jose"),Wt=require("@noble/curves/secp256k1.js"),et=require("@noble/hashes/sha3.js"),Ht=require("@noble/hashes/utils.js");var d=(i=>(i.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",i.AUTH_FAILED="AUTH_FAILED",i.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",i.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",i.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",i.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",i.SESSION_EXPIRED="SESSION_EXPIRED",i.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",i.WALLET_NOT_FOUND="WALLET_NOT_FOUND",i.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",i.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",i.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",i.SIGN_FAILED="SIGN_FAILED",i.SIGN_REJECTED="SIGN_REJECTED",i.TX_FAILED="TX_FAILED",i.TX_REJECTED="TX_REJECTED",i.BROADCAST_FAILED="BROADCAST_FAILED",i.USER_REJECTED="USER_REJECTED",i.TX_INVALID_PARAMS="TX_INVALID_PARAMS",i.NETWORK_ERROR="NETWORK_ERROR",i.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",i.INVALID_CHAIN="INVALID_CHAIN",i.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",i.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",i.NOT_IMPLEMENTED="NOT_IMPLEMENTED",i.SIGNATURE_FAILED="SIGNATURE_FAILED",i.TRANSACTION_FAILED="TRANSACTION_FAILED",i.PREPARE_FAILED="PREPARE_FAILED",i.PREPARE_EXPIRED="PREPARE_EXPIRED",i.PREPARE_MISMATCH="PREPARE_MISMATCH",i.MIGRATION_FAILED="MIGRATION_FAILED",i.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",i.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",i.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",i.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",i.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",i.PROJECT_ID_MISSING="PROJECT_ID_MISSING",i.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",i.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",i.INVALID_APP_TYPE="INVALID_APP_TYPE",i.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",i.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",i.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",i.EXECUTION_REVERTED="EXECUTION_REVERTED",i.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",i.PIN_NOT_SET="PIN_NOT_SET",i.PIN_WRONG="PIN_WRONG",i.PIN_INVALID="PIN_INVALID",i.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",i.PIN_CANCELLED="PIN_CANCELLED",i.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",i.PIN_LOCKED="PIN_LOCKED",i.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",i.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",i.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",i.HMAC_REQUIRED="HMAC_REQUIRED",i.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",i.WITHDRAW_FAILED="WITHDRAW_FAILED",i.USER_NOT_FOUND="USER_NOT_FOUND",i.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",i.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",i.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",i.INVALID_CONFIG="INVALID_CONFIG",i.UNKNOWN_ERROR="UNKNOWN_ERROR",i))(d||{});class u extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,u.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Gt=2e3,tt=6e4,Kt=1e3,Vt=1e4,qt="0x77359400",rt="0x3B9ACA00",st=130,Ke=6,it=18,nt=3e4,zt=300*1e3,jt=30*1e3,Te=100,Yt=300*1e3,ot=60*1e3,Xt="crossx-sdk-js/2.5.0",Ne="ONEpocket";var he=(i=>(i.MetaMask="io.metamask",i.Binance="com.binance.wallet",i.CROSSx="crossx",i))(he||{});const Jt={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:Ne},yt=["crossx","io.metamask","com.binance.wallet"];function bt(i){return Jt[i]??i}function Zt(i){return Array.isArray(i.connectOtherWallets)&&i.connectOtherWallets.length>0?[...i.connectOtherWallets]:i.showConnectOtherWallets===!0?[...yt]:[]}function St(i){const e=i instanceof Error?i.message:String(i);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const Qt=new Set(["ERR_USER_REJECTED","USER_REJECTED","USER_REJECT"]),er=/user rejected|rejected the request|request (?:was )?cancell?ed|entry was cancell?ed|거부했습니다|취소되었습니다/i;function vt(i){if(!i||typeof i!="object")return;const e=i.code;return typeof e=="string"&&e.length>0?e:void 0}function tr(i){const e=vt(i);if(e)return Qt.has(e);const r=i instanceof Error?i.message:String(i);return er.test(r)}function de(i,e){if(i instanceof u)return i;const r=vt(i),t=i instanceof Error?i.message:String(i),s={nativeCode:r,cause:i};if(tr(i))return new u(d.USER_REJECTED,t,s);const n=r&&!t.includes(r)?`${t} (${r})`:t;return new u(e,n,s)}const Ce={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}},rr=Object.fromEntries(Object.entries(Ce).map(([i,e])=>[i,e.caipId])),sr=new Map(Object.values(Ce).map(i=>[i.caipId,i]));new Map(Object.values(Ce).map(i=>[i.chainId,i]));const ir={symbol:"",decimals:18};function nr(i,e){var r;return(e==null?void 0:e[i])??((r=sr.get(i))==null?void 0:r.nativeCurrency)}class Ve{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 u(d.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new u(d.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(s=>s(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let Z=null;function at(i){Z=i}const c={info(...i){if(Z){Z.log(...i);return}console.log(...i)},log(...i){if(Z){Z.log(...i);return}},warn(...i){if(Z){Z.warn(...i);return}},error(...i){if(Z){Z.error(...i);return}}},or={confirm:"확인",cancel:"취소",close:"닫기",signature_requesting:"이(가) 서명을 요청합니다",signature_warning:"서명 후에는 변경하거나 취소할 수 없습니다.",signature_sign_button:"서명",sign_message_title:"서명 요청",sign_typed_data_title:"서명 요청",sign_transaction_title:"서명 요청",send_transaction_title:"트랜잭션 승인",send_tx_permission_text:"이(가) 다음 트랜잭션 승인을 요청합니다.",send_tx_approve_button:"승인",send_tx_confirm_button:"확인",tx_pending:"트랜잭션을 처리하고 있습니다...",tx_success:"트랜잭션 완료",tx_failed:"트랜잭션 실패",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",tx_progress_waiting_title:"확인 대기 중",tx_progress_waiting_text:"트랜잭션 영수증을 기다리는 중...",tx_complete_done_button:"모두 완료",label_to:"받는 주소",label_from:"보내는 주소",label_network:"네트워크",label_value:"금액",label_estimated_fee:"예상 수수료",label_est_tx_fee:"예상 수수료",label_max_priority_fee:"최대 우선 수수료",label_max_gas_fee:"최대 가스 수수료",label_gas_price:"가스 가격",label_gas_limit:"가스 한도",label_transfer:"전송량",label_tx_fee:"수수료",label_tx_hash:"Tx 해시",label_total:"합계",label_including_fees:"(수수료 포함)",label_primary_type:"Primary Type",login_selector_title:"로그인 방법 선택",login_selector_subtitle:"소셜 계정으로 간편하게 로그인하세요",login_selector_google:"Google로 로그인",login_selector_apple:"Apple로 로그인",login_selector_or:"또는",login_selector_terms_template:"계속 진행하면 NEXUS {tos}에 동의하고 {pp}에 동의하게 됩니다.",login_selector_terms_tos:"이용약관",login_selector_terms_pp:"개인정보 처리방침",login_selector_connect_other_wallets:"다른 지갑으로 연결",login_selector_connect_other_wallets_desc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_found_title:"소셜 계정에서 지갑 발견",migration_found_description:`소셜 계정에 연결된 지갑을 발견했습니다.
2
2
  4자리 PIN을 입력하여 자산을 복원하세요.`,migration_recover_button:"내 지갑 복구",migration_skip_button:"나중에 하기",recovery_pin_input_title:"내 지갑 복구",recovery_pin_input_placeholder:"지갑 복구를 위해 4자리 PIN을 입력하세요.",recovery_pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",wallet_selector_title:"연결된 지갑 선택",wallet_selector_description:"이전에 이 게임에서 사용한 지갑을 선택해야 계속 진행할 수 있습니다.",wallet_selector_info_title:"왜 지갑을 선택해야 하나요?",wallet_selector_info_desc:"이전에 연결된 지갑을 확인하면 게임 진행 상황과 자산이 올바르게 동기화됩니다.",wallet_selector_add_button:"지갑 추가",wallet_selector_selected:"선택됨",wallet_selector_add_error_limit_exceeded:"계정 한도에 도달했습니다. 최대 {limit}개의 계정을 사용할 수 있습니다.",wallet_selector_add_error_generic:"새 계정을 추가하지 못했습니다. 다시 시도해 주세요.",wallet_created_title:"지갑이 생성되었습니다!",wallet_created_button:"확인",pin_notice_header_subtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pin_notice_title:"PIN 설정 주의사항",pin_notice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pin_notice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pin_notice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pin_notice_next_button:"확인했습니다",pin_notice_submit_button:"확인했습니다",pin_setup_title:"PIN 만들기",pin_setup_header_subtitle:"이 PIN은 거래 승인에 사용됩니다.",pin_setup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pin_setup_confirm_title:"PIN 확인",pin_setup_confirm_subtitle:"6자리 PIN을 다시 입력하세요.",pin_setup_mismatch_error:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pin_validation_too_short:"6자리 PIN을 입력해 주세요.",pin_validation_numbers_only:"숫자(0-9)만 입력할 수 있습니다.",pin_validation_repeating_digit:"동일한 숫자를 3회 이상 연속으로 사용할 수 없습니다.",pin_validation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pin_validation_alternating_pattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pin_input_title:"PIN 입력",pin_input_subtitle:"거래 승인을 위해 PIN을 입력해 주세요.",pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verify_pin_title:"PIN 확인",verify_pin_subtitle:"계속하려면 PIN을 확인해 주세요.",pin_locked_message:"잠금이 해제된 후 다시 시도해 주세요.",pin_locked_available_from:"(%@ 이후 이용 가능)",pin_locked_failure_warning:"추가 실패 시 계정이 잠금됩니다.",pin_locked_permanent:"계정이 영구 잠금되었습니다. 고객센터에 문의해 주세요.",alert_session_expired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_account_withdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_wallet_not_found:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_different_account:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
3
3
 
4
- 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},vt={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:Te,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 계정으로만 이어서 사용할 수 있습니다.`,session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},Et={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:Ne,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.
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"},rr={ko:tr,en:vt};function Q(i="en",e){return rr[i]??vt}function sr(i){return i==="ko"||i==="en"?i:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const at="crossx_access_token",ct="crossx_refresh_token",lt="crossx_user_info",ke=class ke{constructor(e,r,t,s,n,o,a,l,p=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=s,this.transport=n,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=l,this.getLocale=p,this._refreshPromise=null,this._migrated=!1;const h=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${h}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${h}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${h}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${h}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new u(d.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const s=e==null?void 0:e.provider;let n="/login";s==="google"?n="/google":s==="apple"&&(n="/apple");const{oauthServiceUrl:o,legacyOauthServiceUrl:a}=this.config,l=sr(this.getLocale()),p=w=>{const f=`${w}${n}`,x=f.includes("?")?"&":"?";return`${f}${x}locale=${l}`},h=p(o),_=a?p(a):void 0;c.log(`[CROSSx] OAuth 팝업 열기 (${s||"일반"} 로그인)`),c.log(`[CROSSx] Auth URL: ${h}`);const g=await this.oauth.openAuth({authUrl:h,..._?{legacyAuthUrl:_}:{},expectedOrigin:new URL(o).origin});r=g.token,t=g.email,c.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&c.log("[CROSSx] OAuth 콜백 email:",t)}catch(s){if(c.error("[CROSSx] SignIn 에러 (OAuth 단계):",s),s instanceof u)throw s;const n=s instanceof Error?s.message:"Sign in failed";throw/팝업|popup/i.test(n)?new u(d.OAUTH_POPUP_BLOCKED,n):new u(d.AUTH_FAILED,n)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return c.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return c.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,s,n;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let l,p;try{const h=this.crypto.decodeJWT(e.idToken);p=e.provider??((t=h.firebase)==null?void 0:t.sign_in_provider);const _=((s=h.firebase)==null?void 0:s.identities)??{};l=h.email??((n=_.email)==null?void 0:n[0]),c.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",p,"email:",l??"(없음)")}catch{c.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const h=await this.crypto.verifyJWT(a);if(!h.valid)throw new u(d.AUTH_FAILED,"Access token 검증 실패");const _=h.payload;r={id:_.sub,email:_.email??l,signInProvider:p,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),c.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),c.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new u(d.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),l=o instanceof Error?o.stack:void 0,p=o instanceof Error?o.name:"UnknownError";return c.error("[CROSSx] RN Bridge 로그인 실패 — name:",p,"message:",a,"stack:",l),{success:!1,error:a||"RN Bridge login failed"}}return c.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var n,o,a,l,p;let t,s=!1;try{const{authApiUrl:h}=this.config,{accessToken:_,refreshToken:g}=await this.exchangeFirebaseToken(e,h);let w,f,x;try{const b=this.crypto.decodeJWT(e);c.log("[CROSSx] Firebase JWT 필드:",Object.keys(b).join(", ")),f=(n=b.firebase)==null?void 0:n.sign_in_provider;const E=((o=b.firebase)==null?void 0:o.identities)??{};x=b.email??((a=E.email)==null?void 0:a[0]),f==="google.com"?w=(l=E["google.com"])==null?void 0:l[0]:f==="apple.com"&&(w=(p=E["apple.com"])==null?void 0:p[0]),c.log("[CROSSx] OAuth provider sub 추출 — provider:",f,"hasProviderSub:",!!w,"email:",x??"(없음)")}catch{c.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(_){const b=this.crypto.decodeJWT(_);c.log("[CROSSx] access_token 디코딩 — sub:",b.sub,"exp:",b.exp,"필드:",Object.keys(b).join(", "));const E=await this.crypto.verifyJWT(_);if(s=E.signatureVerified??!1,!E.valid)throw c.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const A=E.payload,T=A.email??x??r;c.log("[CROSSx] email 소스 — CROSSx JWT:",A.email??"(없음)","/ Firebase JWT:",x??"(없음)","/ OAuth 콜백:",r??"(없음)","→",T??"(없음)"),t={id:A.sub,email:T,signInProvider:f,providerSub:w},this.tokenStore.set(_),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,_),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&c.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const b=this.crypto.decodeJWT(e);t={id:b.sub,email:b.email??r,signInProvider:f,providerSub:w},c.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}c.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const y=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,y),await this.clearStoredRNBridgeSession(),c.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(h){return c.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",h),{success:!1,error:h instanceof Error?h.message:"Sign in failed"}}return c.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,s)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;c.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let s;try{s=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){c.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const l=a instanceof Error?a.message:String(a);throw new u(d.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${l}`,a)}c.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",s.status);const n=s.data;this.checkResponseError(n,"RN Bridge token exchange");const o=this.extractAccessToken(n);if(!o)throw new u(d.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return c.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,s=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;c.log("[CROSSx] Firebase 토큰 교환 요청");const n=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});c.log("[CROSSx] 토큰 교환 응답 — status:",n.status);const o=n.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return c.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new u(d.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");c.log("[CROSSx] access_token 교환 성공");let l;return t||(l=this.extractRefreshToken(o)),{accessToken:a,refreshToken:l}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const n=t.data,o=n.access_token??n.token;if(typeof o=="string")return o}const s=t.access_token??t.token;if(typeof s=="string")return s}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const n=t.data,o=n.refresh_token??n.refresh;if(typeof o=="string")return o}const s=t.refresh_token??t.refresh;if(typeof s=="string")return s}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const s=await this.storage.get(this.STORAGE_KEY_USER);if(s)return c.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(s,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){c.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),s=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(c.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",s?"있음":"없음"),s){t&&this.tokenStore.set(t);const n=await this.silentRefresh(s);c.log("[CROSSx] restoreSession — silentRefresh 결과:",n?"토큰 발급 성공":"토큰 없음"),n&&this.tokenStore.set(n)}else{if(!t)return c.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return c.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;c.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(c.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;c.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return c.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof u&&e.code===d.SESSION_EXPIRED;return c.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,s=`${r}/cross-auth/social/refresh/simple`,n={};if(!t){const h=this.tokenStore.get()??"";h&&(n.access_token=h),e&&(n.refresh_token=e)}const o=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:n,...t?{credentials:"include"}:{}});c.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,l=this.extractResponseErrorCode(a);if(l){const h=ke.REFRESH_RELOGIN_CODES.has(l.code);throw new u(h?d.SESSION_EXPIRED:d.AUTH_FAILED,`토큰 갱신 실패 (코드 ${l.code}): ${l.message}`)}const p=this.extractAccessToken(a);if(t&&!p){c.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!p)throw new u(d.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(p),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p);const h=this.extractRefreshToken(a);h&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,h)}return c.log("[CROSSx] silentRefresh 성공"),p}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){c.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:s}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return s?(this.tokenStore.set(s),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,s),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),c.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof u&&t.code===d.RN_NATIVE_SESSION_EXPIRED&&(c.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(c.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof u&&e.code===d.SESSION_EXPIRED?(c.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):c.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,s=!1;try{let n=await this.crypto.verifyJWT(e);if(s=n.signatureVerified??!1,!n.valid){if(!r)return c.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};c.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return c.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,n=await this.crypto.verifyJWT(e),s=n.signatureVerified??!1,!n.valid)return c.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};c.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=n.payload;c.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",s),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),c.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(n){return c.error("[CROSSx] signInWithJWT 에러:",n),{success:!1,error:n instanceof Error?n.message:"JWT sign in failed"}}return this.loadWallet(t,s)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(lt);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(at);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const s=await this.storage.get(ct);s&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s),await this.storage.remove(lt),await this.storage.remove(at),await this.storage.remove(ct),c.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){c.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,s=!1;try{if(typeof this.walletProvider.checkWallet=="function"){c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const n=await this.walletProvider.checkWallet();if(c.log("[CROSSx] 지갑 상태:",n),n==="migration_required")c.log("[CROSSx] migration_required → needsMigration = true"),s=!0;else if(n==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):c.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){c.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else c.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,c.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(n){if(n instanceof u&&n.code===d.MIGRATION_BACKUP_EXISTS)c.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),s=!0;else{if(n instanceof u&&(n.code===d.PROJECT_NOT_REGISTERED||n.code===d.PROJECT_ID_MISSING||n.code===d.ORIGIN_NOT_ALLOWED))throw c.error("[CROSSx] 프로젝트 설정 에러:",n.message),n;c.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",n)}}return c.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",s),{success:!0,address:t,user:e,needsMigration:s,tokenSignatureVerified:r}}};ke.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let We=ke;class ir{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const s=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${s}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${s}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${s}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class nr{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new u(d.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");c.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return c.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class qe{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const s=new Uint8Array(r.length);for(let n=0;n<r.length;n++)s[n]=r[n]^t[n];r.fill(0),this.xorKey=t,this.encryptedBytes=s}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class or{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const s=await this.chainRegistry.getChain(t),n={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:s.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:n})).data;if(a!=null&&a.error)throw new u(d.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class ar{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(s=>s(r))}removeAllListeners(){this.listeners.clear()}}function cr(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class Y{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return c.log("[RNBridge] Bridge is ready"),!0;await new Promise(s=>setTimeout(s,50))}return c.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await Y.waitForBridgeReady(5e3)||c.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=Y.getBridge(),!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw c.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new u(d.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,c.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=cr(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const s=await this.bridge.handshake(t);if(!s.activated)throw new u(d.AUTH_FAILED,"Bridge handshake rejected by native");const n=typeof s.walletName=="string"?s.walletName.trim():"",o=n.length>0&&n.length<=64?n:void 0,a=s.provider==="google"||s.provider==="apple"?s.provider:void 0;return{isActivated:!0,absoluteTtlMs:s.absoluteTtlMs,idleTtlMs:s.idleTtlMs,protocolVersion:s.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:s.walletAddress,walletName:o,walletProvider:a}}catch(s){throw c.error("[RNBridge] Handshake failed",s),new u(d.AUTH_FAILED,"Bridge handshake failed",s)}}async requestFirebaseIdToken(){if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new u(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof u)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new u(d.USER_REJECTED,"Firebase ID token request rejected by user",e):(c.error("[RNBridge] Firebase token request failed",e),new u(d.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new u(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof u?e:(c.error("[RNBridge] Fresh Firebase token request failed",e),new u(d.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new u(d.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new u(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof u?r:(c.warn("[RNBridge] Session restore Firebase token request failed",r),new u(d.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new u(d.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}const he={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 lr(i){const e=i.environment,r=e&&e in he?he[e]:null;if(!r)return null;const t=i.overrides;if(!t)return r;const s={...r};for(const[n,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(s[n]=o);return s}function Ne(){try{if(typeof __CROSSX_CONFIG__<"u"){const i=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=lr(i);if(e)return e}}catch{}try{const i=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(i&&i in he)return he[i]}catch{}return he.production}function Et(i){let e=i.length;for(;e>0&&i.charCodeAt(e-1)===48;)e--;return i.slice(0,e)}function dr(i,e=Ve){if(!i||i==="0x0"||i==="0x")return"0";try{const r=BigInt(i);if(r===0n)return"0";const t=10n**BigInt(st),s=r/t,o=(r%t).toString().padStart(st,"0"),a=Et(o).slice(0,e);return a?`${s}.${a}`:`${s}`}catch{return"?"}}function Se(i,e,r,t=Ve){if(!(!i||i==="0x"||i==="0x0"))try{const s=BigInt(i);if(s===0n)return;const n=10n**BigInt(r),o=s/n,l=(s%n).toString().padStart(r,"0"),p=Et(l.slice(0,t));return`${p?`${o}.${p}`:`${o}`} ${e}`}catch{return}}function pr(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new u(d.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==rt)throw new u(d.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${rt} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function hr(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new u(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new u(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function ur(i,e){const r=_r(e);if(i==="0"){if(r!==void 0&&r!==0)throw new u(d.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=i.match(/^eip155:(\d+)$/);if(t){const s=Number(t[1]);if(r===void 0)throw new u(d.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${i})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==s)throw new u(d.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${i}, 예상값: ${s})와 일치하지 않습니다`)}}function _r(i){if(i==null||typeof i!="object")return;const e=i.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class de{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new u(d.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),c.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new u(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),c.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,s){var l,p;if((p=(l=this.deps).isRNBridgeMode)!=null&&p.call(l))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){c.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let n,o;this.verifyPinMutex=new Promise((h,_)=>{n=h,o=_});const a=Q(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const _=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s});if(!_)throw new u(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(_),c.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),n();return}const h=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s,onSubmit:async _=>{this.deps.pinStore.set(_);try{return await this.deps.walletProvider.verifyPin(_)?(c.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(g){if(this.deps.pinStore.clear(),g instanceof u){if(g.code===d.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(g.code===d.PIN_INVALID)return{ok:!1,error:g.message};if(g.code===d.PIN_LOCKED)return de.buildPinLockedResult(g,a)}throw g}}});if(!h)throw new u(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(h),c.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),n()}catch(h){if(h instanceof u&&(h.code===d.AUTH_NOT_AUTHENTICATED||h.code===d.AUTH_TOKEN_EXPIRED||h.code===d.SESSION_EXPIRED)&&h.code!==d.SESSION_EXPIRED){const _=Q(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:g?this.deps.maskEmail(g,_.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(h),h}throw o(h),h}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=Q(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(s){if(s instanceof u){if(t=de.parsePinError(s,r),!t)throw s}else throw s}for(;;){c.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(s){if(s instanceof u&&(t=de.parsePinError(s,r),t))continue;throw s}}}static parsePinError(e,r){if(e.code===d.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===d.PIN_INVALID)return{errorMessage:e.message};if(e.code===d.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=de.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:s,...n}=t;return{ok:!1,error:s,...n}}}class xr{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new u(d.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let n;return this.deps.walletProvider.prepare&&(n=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(n)})}}function gr(i){return i==="google"||i==="apple"}class fr{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const s=gr(e.loginType)?{provider:e.loginType}:void 0;let n;try{n=await this.deps.executeSignIn(s)}catch(p){throw this.deps.clearAuthState(),p}if(!n.success)return this.deps.clearAuthState(),n;const o=((r=n.user)==null?void 0:r.providerSub)??null,a=((t=n.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){c.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const p=Q(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:p.session_alert_title,message:p.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,p.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(n);try{await this.deps.loadWalletAfterAuth()}catch{c.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return c.log("[CROSSx] signInAgain: 세션 복구 성공"),n}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=Q(this.deps.getLocale()??"en"),{userEmail:s}=this.deps.getSessionSnapshot(),n=s?this.deps.maskEmail(s,t.session_alert_apple_account):void 0;if(r instanceof u&&r.code===d.WITHDRAW_FAILED){if(c.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof u&&r.code===d.WALLET_NOT_FOUND){if(c.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof u)||r.code!==d.SESSION_EXPIRED)throw r;if(c.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:n})==="signout")throw this.deps.clearAuthState(),new u(d.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new u(d.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class wr{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return c.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const s=this.deps.getUserId();if(!s)return;const n=await this.fetchWalletStatus();if(c.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const o=await this.deps.walletProvider.getAddresses(s);if(o.length>0){let l,p=!1;if(r){const _=o.find(g=>g.address.toLowerCase()===r.toLowerCase());_?l=_:(l={address:r,index:0},p=!0)}else e!==void 0?l=o.find(_=>_.index===e)??o[0]:l=o[0];p?c.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",l.address):c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address);const h=!!r&&!!t&&l.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(l.address,l.index,h?{walletName:t}:void 0);return}c.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(s,0);c.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class mr{constructor(e){this.deps=e}async handleMigrationFlow(e){var l,p;c.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(c.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return c.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let s,n=0,o=5,a=null;for(;;){n++,c.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,s?`— 이전 메시지: ${s}`:"");const h=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:s,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(h===null)return c.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;c.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),s=void 0;try{const _=await((p=(l=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:p.call(l,h,e));if(!_){c.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(_.valid){c.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const g=_.pinStatus;if(o=g.maxAttempts,n=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const w=g.lockExpiresAt*1e3,f=Math.max(1,Math.round((w-Date.now())/1e3)),x=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${f}초, 메시지: ${x}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,x),n=0,s="Your account lock has been lifted. You may try again."}else c.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),s="Incorrect PIN."}catch(_){if(!(_ instanceof u))throw _;if(_.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=Q(this.deps.getLocale()??"en"),w=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:w?this.deps.maskEmail(w,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),n--;continue}throw this.deps.clearAuthState(),_}if(_.code===d.MIGRATION_PIN_LOCKED){const g=_.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return c.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((g==null?void 0:g.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((w-Date.now())/1e3)),x=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${f}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(f,x),n=0,s="Your account lock has been lifted. You may try again."}else throw c.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}c.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const h=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof u&&h.code===d.MIGRATION_FAILED)return c.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(h instanceof u&&h.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=Q(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:g?this.deps.maskEmail(g,_.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const x=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",x.address),x}catch(x){throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",x),x}}throw this.deps.clearAuthState(),h}throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}}class yr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=w=>!(w!=null&&w.trim()),s=e.nonce===void 0||e.nonce===null,n=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!s&&!n&&!o&&!a)return e;const l={...e},p=s?l.from??this.deps.getActiveAddress()??void 0:void 0;p&&c.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",p,")"),n&&c.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&c.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[h,_,g]=await Promise.all([p?this.deps.jsonRpcCall("eth_getTransactionCount",[p,"pending"],r):null,n?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(p&&(l.nonce=parseInt(h??"0x0",16),c.log("[CROSSx] nonce 결과:",l.nonce)),n&&(l.gasLimit=_,c.log("[CROSSx] estimateGas 결과:",l.gasLimit)),o){const w=g;if(w){const f=tt;l.maxFeePerGas=`0x${(BigInt(w)+BigInt(f)).toString(16)}`,l.maxPriorityFeePerGas=f,c.log("[CROSSx] Dynamic 체인 감지 — baseFee:",w,"maxFeePerGas:",l.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else l.gasPrice=Kt,c.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(l.maxPriorityFeePerGas=tt,c.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),l}}class br{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const s=this.crypto.recoverPersonalSignSigner(e,r);if(s.toLowerCase()!==t.toLowerCase())throw c.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:s}),new u(d.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${s}`);c.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(s){if(s instanceof u)throw s;c.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",s)}}}function Sr(i){return i?i.includes("google")?"google":i.includes("apple")?"apple":i:null}class vr{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const s={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(s.walletName=t.walletName),this.deps.emitAddressChanged(s),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e,r){var s,n,o,a,l;const t={authenticated:e.success,userId:((s=e.user)==null?void 0:s.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:Sr((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:((l=e.user)==null?void 0:l.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 Er{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 u(d.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Ar{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new u(d.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new u(d.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Ir{constructor(e){this.deps=e}async createWallet(){var s,n;const e=this.deps.getUserId();if(!e)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");c.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(c.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;c.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 u(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((n=(s=this.deps).showWalletCreated)==null?void 0:n.call(s)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),c.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof u&&r.code===d.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;c.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const s=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(s)return this.deps.setActiveWallet(s.address,0),{address:s.address,migrated:!0};throw new u(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function dt(i,e){const r=i.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class kr{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new u(d.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new u(d.TX_INVALID_PARAMS,"invalid param tx_hash");const s=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(s))throw new u(d.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new u(d.TX_INVALID_PARAMS,"invalid param body");const n=this.deps.getApiBaseUrl(),o=dt(n,`/v2/token-historical/${e}/${s}`),a={clientVersion:t};try{c.log("[TokenHistory] Registering tx:",e,s);const l=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});l.status!==200&&this.handleError(l.status,"register"),c.log("[TokenHistory] Successfully registered:",e,s)}catch(l){throw l instanceof u?l:new u(d.UNKNOWN_ERROR,`Failed to register token history: ${l instanceof Error?l.message:String(l)}`)}}async getTokenHistory(e){var s;const r=this.deps.getApiBaseUrl(),t=new URL(dt(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{c.log("[TokenHistory] Fetching token history");const n=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(n.status===404)throw new u(d.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return n.status!==200&&this.handleError(n.status,"fetch"),c.log("[TokenHistory] Successfully fetched history:",((s=n.data.rows)==null?void 0:s.length)??0,"items"),n.data.rows||[]}catch(n){throw n instanceof u?n:new u(d.UNKNOWN_ERROR,`Failed to fetch token history: ${n instanceof Error?n.message:String(n)}`)}}async registerHistoryFireAndForget(e,r,t,s){const n=(s==null?void 0:s.maxRetries)??3,o=(s==null?void 0:s.retryDelayMs)??2e3;for(let a=0;a<n;a++)try{await this.registerTokenHistory(e,r,t);return}catch(l){if(l instanceof u&&l.message.includes("404")&&a<n-1){c.log(`[TokenHistory] Retry ${a+1}/${n} (404 - tx not yet indexed)`),await new Promise(h=>setTimeout(h,o));continue}throw l}}handleError(e,r){const s={400:{code:d.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:d.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:d.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:d.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new u(s.code,s.message)}}function De(i,e="Apple account"){if(i.endsWith("@privaterelay.appleid.com"))return e;const r=i.indexOf("@");if(r<0)return"*".repeat(i.length||3);const t=i.substring(0,r),s=i.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${s}`:`${t[0]}${"*".repeat(t.length-1)}${s}`}const ce=class ce extends ar{constructor(e,r,t,s,n,o,a,l,p,h,_,g){var w,f;super(),this.storage=t,this.crypto=s,this.transport=n,this.oauth=o,this.walletProvider=a,this.tokenStore=l,this.pinEncryptor=g,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&&ot(e.logger),this.confirmation=p,this.pinStore=_??new qe,this.stateManager=new vr({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:y,walletName:b})=>{const E={address:x,index:y};b!==void 0&&(E.walletName=b),this.emit("addressChanged",E)},emitAuthChanged:({isAuthenticated:x,address:y,userId:b,source:E})=>{this.emit("authChanged",{isAuthenticated:x,address:y,userId:b,...E?{source:E}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:ce.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new de({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:De,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new xr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new wr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,y,b)=>this.setActiveWallet(x,y,b)}),this.migrationOrchestrator=new mr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,y)=>this.migrateWalletUseCase.execute(x,y),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:De,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new yr({getActiveAddress:()=>this.address,estimateGas:(x,y)=>this.estimateGas(x,y),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,y,b)=>this.jsonRpc.call(x,y,b)}),this.signatureVerifier=new br(this.crypto),this.addressResolverService=new Er({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Ar({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Ir({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,y)=>this.setActiveWallet(x,y),showWalletCreated:()=>{var x,y;return((y=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:y.call(x))??Promise.resolve()}}),this.tokenHistoryService=new kr({transport:n,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new fr({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:De}),this.chainRegistry=h,this.jsonRpc=new or(h,n),this.signInUseCase=new We(this.internalConfig,t,s,o,n,a,l,void 0,()=>this._config.locale),this.signOutUseCase=new ir(this.internalConfig,t,l),this.migrateWalletUseCase=new nr(t,a),(w=a.setOnUnauthorized)==null||w.call(a,()=>this.forceLogout()),(f=a.setTokenRefresher)==null||f.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,c.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(r){c.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;c.log("[CROSSx SDK] v2.4.0 초기화 중..."),this.confirmation.setMessages(Q(this._config.locale));try{const s=Ne();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=s.legacyOauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${s.authApiUrl}/.well-known/jwks.json`);const n=this._config.persistWalletPreference!==!1?await this.storage.get(ce.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(n==null?void 0:n.index);let a=(e==null?void 0:e.preferredWalletAddress)??(n==null?void 0:n.address),l=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&c.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),l||(l=await this.signInUseCase.restoreSession()),l!=null&&l.success){this.applyAuthResult(l);const p=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),h=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(p)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,h?{walletName:h}:void 0);else try{await this.loadWalletAfterAuth(o,a,h)}catch(_){if(_ instanceof u&&_.code===d.PIN_CANCELLED)c.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(_ instanceof u&&(_.code===d.SESSION_EXPIRED||_.code===d.AUTH_NOT_AUTHENTICATED||_.code===d.USER_NOT_FOUND))c.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",_.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),l=null;else throw _}}return this.initialized=!0,c.info("[CROSSx SDK] v2.4.0 초기화 완료"),this.emit("initialized",{restored:!!(l!=null&&l.success)}),l??null}catch(s){throw new u(d.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async tryRNBridgeBootstrap(){if(!Y.isAvailable())return null;try{c.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),c.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.4.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new Y({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.4.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),c.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const s=await this._tryBridgeSessionRestore();if(s!=null&&s.success)return s}return c.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return c.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),c.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const r=this._rnBridgeService.getContext(),t=Date.now();c.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 s=Date.now(),n=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=n.walletAddress,this._rnBridgeWalletName=n.walletName,this._rnBridgeWalletProvider=n.walletProvider,c.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-s,walletAddress:n.walletAddress??"(없음)",walletName:n.walletName??"(없음)",absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs})}catch(s){return c.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",s),this._rnBridgeService=null,null}}try{const r=await this._rnBridgeService.requestFirebaseIdToken();c.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),c.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof u&&r.code===d.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),c.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):r instanceof u&&r.code===d.SESSION_EXPIRED?(c.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(c.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;c.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(this._isAuthenticatedViaRNBridge=!1,c.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return this._isAuthenticatedViaRNBridge=!1,c.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new u(d.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw c.error("[CROSSx] Bridge session restore token request failed:",e),new u(d.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return Y.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new u(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&c.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const s=await this._tryBridgeSignIn();if(s===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(s!=null&&s.success)return s}let t=e;if(!(e!=null&&e.provider)){const s=await this.confirmation.showLoginSelector({connectOtherWallets:Jt(this._config)});if(s===null)return{success:!1,error:"User cancelled login"};if(s.type==="external")throw this.emit("connectExternalWallet",{walletId:s.walletId}),new u(d.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:s.provider}}try{const s=await this.signInUseCase.execute(t);return s.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(s)),s}catch(s){throw s instanceof u?s:new u(d.AUTH_FAILED,"로그인에 실패했습니다",s)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},s=await this.signIn(t);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:a}=await this.createWallet(),l=await this.getAddresses(),p=await this.selectWalletIfMultiple(l,r);return{...s,address:(p==null?void 0:p.address)??a,needsMigration:!1,addresses:l}}const n=await this.getAddresses(),o=await this.selectWalletIfMultiple(n,r);return{...s,address:(o==null?void 0:o.address)??s.address,addresses:n}}catch(n){throw n instanceof u&&n.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>c.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),n}}async signInWithOAuthToken(e){var t,s;if(this.ensureInitialized(),this.authenticated)throw new u(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r,"external"),(s=(t=this.oauth).cancelPending)==null||s.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(n){throw n instanceof u?n:new u(d.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",n)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),l=await this.getAddresses(),p=await this.selectWalletIfMultiple(l);return{...r,address:(p==null?void 0:p.address)??a,needsMigration:!1,addresses:l}}const n=await this.getAddresses(),o=await this.selectWalletIfMultiple(n);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:n}}catch(n){throw n instanceof u&&n.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>c.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),n}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new u(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof u?t:new u(d.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=Y.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),c.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){c.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new u(d.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof u&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof u&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),c.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof u?r:new u(d.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const s=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,s)))).address,index:s};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(s=>s.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof u?e:new u(d.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof u?r:new u(d.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=s=>{const n=s?"dark":"light";this.applyTheme(n,this._config.themeTokens??{})};r(e.matches);const t=s=>r(s.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Q(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const s=Y.getBridge(),n=this._isAuthenticatedViaRNBridge||!this.authenticated;if(s!=null&&s.signMessage&&n)try{const a=await s.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:a.signature,message:r,address:this.address??""}}catch(a){if(!bt(a))throw a;await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),c.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new u(d.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:l=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,l,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 u?a:new u(d.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 u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new u(d.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ur(e,r);const s=await this.resolveAddress(t==null?void 0:t.index);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:s.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:s.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,s.address)});return pr(n.signature),{chainId:e,signature:n.signature,address:s.address}}catch(n){throw n instanceof u?n:new u(d.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,n)}}async signTypedDataOffchain(e,r){return this.signTypedData(ce.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 u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const n=Oe(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:n.symbol,nativeDecimals:n.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:s},execute:a=>this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,a)});return hr(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof u)throw o;const a=o instanceof Error?o.message:String(o);throw new u(d.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 u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const n=Oe(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:n.symbol,nativeDecimals:n.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:s},execute:async h=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,s,h)).txHash;const _=await this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,h);return _.txHash??_.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),l=a===""||a==="00000000",p=a.startsWith("a9059cbb");return(l||p)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Yt).catch(h=>c.log("[TokenHistory] register failed (non-critical):",h)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof u)throw o;const a=o instanceof Error?o.message:String(o);throw new u(d.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 s=t.intervalMs??Ht,n=Gt,o=t.timeoutMs??et,a=Date.now()+o;let l=s;for(;Date.now()<a;){const p=await this.getTransactionReceipt(e,r);if(p)return p;await new Promise(h=>setTimeout(h,l)),l=Math.min(l*2,n)}throw new u(d.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var x,y;if(this._isAuthenticatedViaRNBridge){const b=Y.getBridge();if(b!=null&&b.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(b,e,r,t)}const{intervalMs:s,timeoutMs:n,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),l=s??((x=this._config.receiptPolling)==null?void 0:x.intervalMs)??Wt,p=n??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??et,h=Oe(e),_=r.from??"";let g,w;const f=this.waitForTxAndGetReceipt(a,e,{intervalMs:l,timeoutMs:p}).then(b=>{g=b;const E=BigInt(b.gasUsed)*BigInt(b.effectiveGasPrice),A=r.value?BigInt(r.value):0n,T=Se(r.value,h.symbol,h.decimals,this._config.displayDecimals),R=Se("0x"+E.toString(16),h.symbol,h.decimals,this._config.displayDecimals),D=Se("0x"+(A+E).toString(16),h.symbol,h.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:b.from,to:b.to??r.to,amount:T,fees:R,total:D,nativeSymbol:h.symbol,status:b.status==="0x1"?"success":"reverted"}}).catch(b=>(w=b instanceof Error?b:new Error(String(b)),{chainId:e,txHash:a,from:_,to:r.to,amount:Se(r.value,h.symbol,h.decimals,this._config.displayDecimals),nativeSymbol:h.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:_,to:r.to},f),w)throw w;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,s){const n=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:s.dappName??this._config.appName,accountName:s.accountName,index:s.index,timeoutMs:s.timeoutMs,pollIntervalMs:s.intervalMs});return{chainId:r,txHash:n.txHash,receipt:{transactionHash:n.txHash,blockHash:n.blockHash??"",blockNumber:n.blockNumber??"",from:n.from??t.from??"",to:n.to??null,gasUsed:n.gasUsed??"0x0",effectiveGasPrice:n.effectiveGasPrice??"0x0",status:n.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 u(d.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),c.log("[CROSSx] PIN 변경 완료")}catch(s){throw s instanceof u?s:new u(d.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",s)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new u(d.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(s){const n=s instanceof Error?s.message:String(s);throw new u(d.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${n}`,s)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new u(d.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new u(d.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof u)throw t;const s=t instanceof Error?t.message:String(t);throw new u(d.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${s}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const s=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:s,formatted:dr(s,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof u)throw t;const s=t instanceof Error?t.message:String(t);throw new u(d.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${s}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new St(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){c.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(s){if(s instanceof u)throw s;const n=s instanceof Error?s.message:String(s);throw new u(d.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${n}`,s)}}setActiveWallet(e,r,t){const s=this.address;this.stateManager.setActiveWallet(e,r,t),s&&e&&s.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=Y.getBridge();if(!(e!=null&&e.onEvent)){c.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){c.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){c.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,s=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(s)){c.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){c.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){c.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const n=typeof t.walletName=="string"?t.walletName.trim():"",o=n.length>0&&n.length<=64?n:void 0;this.address&&this.address.toLowerCase()===s.toLowerCase()||(c.log("[CROSSx] Native walletChanged 수신",{address:s,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(s,0,{walletName:o}),this._rnBridgeWalletAddress=s,this._rnBridgeWalletName=o)}),c.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,r){this.stateManager.applyAuthResult(e,r)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(c.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),ot(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}}};ce.WALLET_PREF_KEY="wallet_preference",ce.OFFCHAIN_CHAIN_ID="0";let Ae=ce;class Tr{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw c.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return c.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw c.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw c.error("Storage clear error:",e),e}}}const Le="crossx-sdk",Rr=1,j="data",ie="keys",ve="aes-primary",Nr=12;class pt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const s=indexedDB.open(e,Rr);s.onupgradeneeded=()=>{const n=s.result;n.objectStoreNames.contains(j)||n.createObjectStore(j),n.objectStoreNames.contains(ie)||n.createObjectStore(ie)},s.onsuccess=()=>r(s.result),s.onerror=()=>t(s.error)})}idbGet(e,r){return new Promise((t,s)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>s(o.error)})}idbPut(e,r,t){return new Promise((s,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>s(),a.onerror=()=>n(a.error)})}idbDelete(e,r){return new Promise((t,s)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>s(o.error)})}idbClear(e){return new Promise((r,t)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).clear();n.onsuccess=()=>r(),n.onerror=()=>t(n.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(ie,ve);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(ie,ve,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Le)return null;try{const e=await this.openDB(Le),r=e.transaction([ie,j],"readonly"),t=r.objectStore(ie).get(ve),s=await new Promise((p,h)=>{t.onsuccess=()=>p(t.result),t.onerror=()=>h(t.error)});if(!s)return e.close(),null;const n=r.objectStore(j).getAll(),o=r.objectStore(j).getAllKeys(),[a,l]=await Promise.all([new Promise((p,h)=>{n.onsuccess=()=>p(n.result),n.onerror=()=>h(n.error)}),new Promise((p,h)=>{o.onsuccess=()=>p(o.result),o.onerror=()=>h(o.error)})]);e.close(),await this.idbPut(ie,ve,s);for(let p=0;p<l.length;p++)await this.idbPut(j,String(l[p]),a[p]);return indexedDB.deleteDatabase(Le),c.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),s}catch(e){return c.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Nr);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:s}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),s=await this.encrypt(t);await this.idbPut(j,e,s)}catch(t){throw c.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(j,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return c.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(j,e)}catch(r){throw c.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(j)}catch(e){throw c.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Pr=60;class Cr{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Ce.createRemoteJWKSet(new URL(e)),c.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){c.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);c.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const s=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Pr<s)return c.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:s,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return c.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:n}=await Ce.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return c.log("[CROSSx] JWT 서명 검증 성공"),{payload:n,valid:!0,signatureVerified:!0}}catch(n){if(n instanceof Error&&(n.name==="JWSSignatureVerificationFailed"||n.name==="JWTClaimValidationFailed"))return c.error("[CROSSx] JWT 서명 검증 실패:",n),{payload:t,valid:!1,signatureVerified:!1};c.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return c.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw c.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ce.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),s=new TextEncoder().encode(`Ethereum Signed Message:
7
- ${t.length}`),n=new Uint8Array(s.length+t.length);n.set(s,0),n.set(t,s.length);const o=Qe.keccak_256(n),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const l=Or(a),p=l.slice(0,32),h=l.slice(32,64),_=l[64],g=_>=27?_-27:_,x=new Bt.secp256k1.Signature(ht(p),ht(h)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),y=Qe.keccak_256(x);return"0x"+Ut.bytesToHex(y.slice(12))}}function Or(i){const e=new Uint8Array(i.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(i.substring(r*2,r*2+2),16);return e}function ht(i){let e="0x";for(const r of i)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const ut=5e3,Dr="sdk-flags.json";class Lr{constructor(e,r){this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyInFlight=null,this.keyFailedAt=0,this.cachedMode=null,this.modeResolvedAt=0,this.modeInFlight=null,this.required=!1,this.adapterConfig=e,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async seal(e){if(!e)return e;const r=await this.resolveMode();if(r==="off")return e;const t=r==="on"||this.required;if(!t&&this.hasFreshFailure())return e;try{const{version:s,key:n}=await this.currentKey(),o=await Mr(n,e);return`${s}.${Fr(o)}`}catch(s){if(t)throw this.keyFailedAt=Date.now(),s instanceof u?s:new u(d.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(s)});return this.keyFailedAt=Date.now(),c.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(nt/1e3)}초 후 재확인)`),e}}invalidate(){c.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(c.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.resolveMode().then(e=>{if(e!=="off")return this.currentKey().then(()=>{},()=>{})}).catch(()=>{})}async resolveMode(){return this.cachedMode&&Date.now()-this.modeResolvedAt<jt?this.cachedMode:this.modeInFlight?this.modeInFlight:(this.modeInFlight=this.fetchRemoteMode().then(e=>(this.cachedMode=e,this.modeResolvedAt=Date.now(),e)).finally(()=>{this.modeInFlight=null}),this.modeInFlight)}async fetchRemoteMode(){let e;try{e=`${Ne().contentsBaseUrl}/${Dr}`}catch{return"auto"}try{const r=await this.transport.request({url:e,method:"GET",timeoutMs:ut}),t=typeof r.data=="string"?Wr(r.data):r.data,s=t==null?void 0:t.pinEncryption;if(s==="auto"||s==="on"||s==="off")return c.log("[CROSSx] 운영 플래그 pinEncryption =",s),s}catch{}return"auto"}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<nt}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<zt?{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,c.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=At();if(!e)throw new u(d.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:ut}),t=Hr(r.data);if(!(t!=null&&t.keyVersion)||!(t!=null&&t.publicKey))throw new u(d.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const s=Br(t.publicKey),n=await e.importKey("spki",Ur(s),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:t.keyVersion,key:n}}}async function Mr(i,e){const r=At();if(!r)throw new u(d.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const t=await r.encrypt({name:"RSA-OAEP"},i,new TextEncoder().encode(e));return new Uint8Array(t)}function At(){const i=globalThis.crypto;return(i==null?void 0:i.subtle)??null}function Fr(i){return $r(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const fe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function $r(i){let e="";for(let r=0;r<i.length;r+=3){const t=i[r],s=i[r+1],n=i[r+2];e+=fe[t>>2],e+=fe[(t&3)<<4|(s??0)>>4],e+=s===void 0?"=":fe[(s&15)<<2|(n??0)>>6],e+=n===void 0?"=":fe[n&63]}return e}function Br(i){const e=i.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 s=0;s<r.length;s+=4){const n=[0,1,2,3].map(o=>{const a=r[s+o];if(a==="="||a===void 0)return-1;const l=fe.indexOf(a);if(l===-1)throw new u(d.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return l});t.push((n[0]&63)<<2|(n[1]&63)>>4),n[2]!==-1&&t.push((n[1]&15)<<4|(n[2]&63)>>2),n[3]!==-1&&t.push((n[2]&3)<<6|n[3]&63)}return new Uint8Array(t)}function Ur(i){const e=new Uint8Array(i.length);return e.set(i),e.buffer}function Wr(i){try{return JSON.parse(i)}catch{return null}}function Hr(i){if(!i||typeof i!="object")return null;const e=i;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new u(d.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 Gr=3e4,Kr=1e3;class Vr{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const s=await this._doRequest(e);if(s.status<500||t===r)return s}catch(s){if(t===r)throw s}await new Promise(s=>setTimeout(s,Kr*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Gr);try{const s=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let n;const o=await s.text();try{n=o?JSON.parse(o):null}catch{n={_raw:o}}return{status:s.status,data:n,headers:Object.fromEntries(s.headers.entries())}}finally{clearTimeout(t)}}}const qr=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function ze(){return typeof window>"u"?void 0:window}function zr(){const i=ze();return i==null?void 0:i.__crossx}function jr(i){return i==="ios"||i==="android"?i:null}function Me(){const i=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(i)?"android":/iPhone|iPad|iPod|Macintosh/i.test(i)?"ios":null}function Yr(i,e){const r=o=>o.split(/[^\d]+/).filter(a=>a!=="").map(a=>Number.parseInt(a,10)),t=r(i),s=r(e),n=Math.max(t.length,s.length);for(let o=0;o<n;o+=1){const a=(t[o]??0)-(s[o]??0);if(a!==0)return a}return 0}function Xr(){const i=ze();if(!i)return!1;const e=i.__crossxRNBridge;return e!=null&&e.isInstalled?!0:i.__CROSSX_BRIDGE_INITIALIZED__===!0||i.__CROSSX_RN_BRIDGE_READY__===!0}function _t(){const i=typeof navigator>"u"?"":navigator.userAgent;for(const e of qr){const r=e.exec(i);if(r)return r[1]??null}}function me(){const i=zr();if(i!=null&&i.browser)return{version:i.version??null,platform:jr(i.platform)??Me(),detectedBy:"marker"};if(Xr())return{version:_t()??null,platform:Me(),detectedBy:"bridge"};const e=_t();return e!==void 0?{version:e,platform:Me(),detectedBy:"user-agent"}:null}function Jr(){return me()!==null}function Zr(i=3e3){const e=me();return e?Promise.resolve(e):ze()?new Promise(r=>{const t=Date.now(),s=setInterval(()=>{const n=me();if(n){clearInterval(s),r(n);return}Date.now()-t>=i&&(clearInterval(s),r(null))},50)}):Promise.resolve(null)}const Qr=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"]),es="crossx://oauth-callback",ts="2.3.2";function rs(i){return i.platform!=="ios"?!1:i.version?Yr(i.version,ts)<=0:!0}class oe{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(c.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,"/"),s=atob(t);return JSON.parse(s)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),s=>s.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=oe.parseJwtPayload(e),s=t.nonce,n=typeof t.iss=="string"?t.iss:"(unknown)";if(c.log("[CROSSx] nonce 검증 시작 —",{iss:n,nonceClaimType:typeof s,nonceClaimPresent:typeof s=="string"&&s!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),n.includes("securetoken.google.com")){c.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof s!="string"||s===""){c.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:n,keys:Object.keys(t)});return}if(n.includes("appleid.apple.com")){const o=await oe.sha256Hex(r);if(c.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:s.length,match:s===o}),s!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(c.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:s.length,match:s===r}),s!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");c.log("[CROSSx] nonce 검증 성공 —",{iss:n})}openAuth(e){return new Promise((r,t)=>{const s=Math.max(e.width??500,500),n=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-s)/2,a=window.screenY+(window.outerHeight-n)/2,l=oe.generateRandom16Hex(),p=oe.generateRandom16Hex(),h=me();let _=e.authUrl;h&&e.legacyAuthUrl&&rs(h)&&(_=e.legacyAuthUrl,c.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:h.version??"(unknown)",detectedBy:h.detectedBy,authUrlBase:e.legacyAuthUrl}));const g=_.includes("?")?"&":"?",w=encodeURIComponent(window.location.origin);let f=`${_}${g}state=${l}&nonce=${p}&origin=${w}`;h&&!f.includes("redirectUrl=")&&(f+=`&redirectUrl=${encodeURIComponent(es)}`,c.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:h.detectedBy,appVersion:h.version??"(unknown)",platform:h.platform??"(unknown)"})),c.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:l.length,nonceLength:p.length,authUrlBase:_});const x=window.open(f,h?"_blank":"CROSSx OAuth",`width=${s},height=${n},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const y=setTimeout(()=>{c.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),F(),t(new Error("Authentication timeout"))},5*60*1e3),b=10,E=30;let A=0,T=null;const R=()=>{clearInterval(D),c.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),T=setTimeout(()=>{F(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},D=setInterval(()=>{A++;try{if(!x.closed)return;if(!!h){F(),t(new u(d.USER_REJECTED,"로그인이 취소되었습니다"));return}const K=typeof document<"u"&&document.hasFocus();A<=b&&!K?R():(F(),t(new u(d.USER_REJECTED,"로그인이 취소되었습니다")))}catch{R()}},1e3),F=()=>{this.abortPending=null,clearTimeout(y),clearInterval(D),T&&clearTimeout(T),window.removeEventListener("message",C)},C=O=>{if(!Qr.has(O.origin))return;F();const K=typeof O.data.status=="string",I=K?O.data.data??{}:O.data;c.log("[CROSSx] OAuth postMessage 수신 —",{format:K?"wrapped":"flat",status:K?O.data.status:"(flat)"});const L=(I==null?void 0:I.state)??O.data.state;if(!L||L!==l){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(K&&O.data.status!=="success"){c.error("[CROSSx] OAuth 실패:",I==null?void 0:I.error),t(new Error((I==null?void 0:I.error)||"Authentication failed"));return}if(!K&&(I!=null&&I.error)){c.error("[CROSSx] OAuth 실패:",I.error),t(new Error(I.error||"Authentication failed"));return}const $=I==null?void 0:I.idToken,X=I==null?void 0:I.accessToken,ue=X??$,ye=(I==null?void 0:I.email)||void 0;if(c.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!X,hasIdToken:!!$,hasEmail:!!ye}),!ue){c.error("[CROSSx] 토큰을 찾을 수 없음:",O.data),t(new Error("Token not found in response"));return}const _e={token:ue,email:ye},se=xe=>{oe.verifyIdTokenNonce(xe,p).then(()=>r(_e)).catch(J=>{c.error("[CROSSx] nonce 검증 실패:",J),t(J instanceof Error?J:new Error("nonce verification failed"))})};X?X.split(".").length===3?se(X):$?se($):(c.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(_e)):$?se($):t(new Error("Token not found in response"))};this.abortPending=O=>{F(),t(new Error(O))},window.addEventListener("message",C)})}}const ge="crossx_wallet_data",le="crossx_mock_pin_hash";class ss{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return c.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(ge)?"exists":"not_found";return c.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(ge);if(t)return t;const s={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ge,s);const n=(r=this.pinStore)==null?void 0:r.get();return n&&(await this.storage.set(le,n),c.log("[Mock] 지갑 생성 — PIN 저장됨")),s}catch(t){throw new u(d.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(ge);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return c.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,s=0,n,o){return c.log(`[Mock] signMessage chainId=${r} index=${s} uuid=${n} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,s=0,n,o){return c.log(`[Mock] signTypedData chainId=${r} index=${s} uuid=${n} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,s=0,n){c.log(`[Mock] signTransaction chainId=${r} index=${s} uuid=${n}:`,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,s){return c.log(`[Mock] sendTransaction chainId=${r} uuid=${s}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(c.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(le);return r&&r!==e?!1:(r||await this.storage.set(le,e),(t=this.pinStore)==null||t.set(e),c.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var n;if(c.log("[Mock] changePin"),this.pinScenario==="wrong")throw new u(d.PIN_WRONG,"Incorrect PIN.");const t=(n=this.pinStore)==null?void 0:n.get(),s=await this.storage.get(le);if(s&&t&&s!==t)throw new u(d.PIN_WRONG,"Incorrect PIN.");await this.storage.set(le,r),c.log("[Mock] changePin 완료")}async migrateWallet(e,r){var n;if(c.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new u(d.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new u(d.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ge,t);const s=(n=this.pinStore)==null?void 0:n.get();return s&&(await this.storage.set(le,s),c.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return c.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return c.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}const is=["password","newPassword","recoveryPin"];class ae{constructor(e,r,t,s,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=s,this.pinStore=n??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(it))return e;const r=!e||this.tokenStore.isExpiringSoon(it);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const s=this.tokenStore.get();if(s)return s}if(r)throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return c.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(c.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 is){const s=e[t];if(typeof s!="string"||s==="")continue;const n=await this.pinEncryptor.seal(s);n!==s&&(r||(r={...e}),r[t]=n)}return r??e}async request(e,r,t,s=!1,n=!1){var h,_,g,w;const o=await this.ensureValidToken(),a=`${this.baseUrl}${r}`,l={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId},p=await this.sealPinFields(t);try{const x=(await this.transport.request({url:a,method:e,headers:l,body:p??void 0})).data;if(x&&typeof x.code=="number"){if(x.code<0||x.code>=400){const y=x.message||x.data||"API 요청에 실패했습니다";c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:x.code,message:y,url:a,method:e});const b=ae.mapGatewayError(x.code,x.data);if(b===d.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!n))return c.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,r,t,s,!0);if(b===d.AUTH_NOT_AUTHENTICATED&&!s&&this._onTokenRefresh){if(c.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0,n);throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(b===d.USER_NOT_FOUND)throw c.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(h=this._onUnauthorized)==null||h.call(this),new u(d.USER_NOT_FOUND,ae.getGatewayErrorMessage(x.code,y));const E=b===d.AUTH_NOT_AUTHENTICATED?d.SESSION_EXPIRED:b,A=E===d.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":ae.getGatewayErrorMessage(x.code,y),T=x.data;let R;throw b===d.PIN_LOCKED?R=ae.extractLockDetails(T):b===d.ADDRESS_LIMIT_EXCEEDED?R={limit:Ee,raw:T}:R=T??void 0,new u(E,A,R)}return c.log("[CROSSx] Wallet Gateway API 성공:",{code:x.code,url:a,method:e}),x.data??x}return x}catch(f){if(f instanceof u)throw f;const x=((_=f.response)==null?void 0:_.status)??f.status;if((x===401||x===403)&&!s&&this._onTokenRefresh){if(c.warn(`[CROSSx] HTTP ${x} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0,n);throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((g=f.response)!=null&&g.data){const y=f.response.data,b=y.message||y.data||"API 요청에 실패했습니다",E=y.code||"UNKNOWN";throw c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:b,url:a,method:e,status:(w=f.response)==null?void 0:w.status}),new u(d.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${b}`)}throw f}}async checkWallet(){var r,t;c.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 c.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,c.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw c.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new u(d.MIGRATION_BACKUP_EXISTS,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){c.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const n=await this.getAddress(e,0);return c.log("[CROSSx] 주소 조회 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}c.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},s=await this.request("POST","/mnemonic/create",t);return c.log("[CROSSx] /mnemonic/create 완료 — address:",s.address),{id:e,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new u(d.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new u(d.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new u(d.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const s={action:e,params:t},n=await this.request("POST","/mnemonic/prepare",s);return{uuid:n.uuid,expiresAt:n.expiresAt}}async signMessage(e,r,t,s,n,o){const a={message:t,password:this.requirePin()};n&&(a.uuid=n),o&&(a.from=o);const l=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:l.signature,format:"hex"}}async signTypedData(e,r,t,s,n,o){const a={typedData:t,password:this.requirePin()};n&&(a.uuid=n),o&&(a.from=o);const l=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:l.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,s,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};n&&(o.uuid=n);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,s){const n={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return s&&(n.uuid=s),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,n)).txHash}}async migrateWallet(e,r){c.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},s=await this.request("POST","/mnemonic/migrate",t);return c.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",s.address),{id:r,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const s=t.passwordStatus;if(s.permanent)throw new u(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:s.lockExpiresAt,remainingAttempts:0,maxAttempts:s.maxAttempts});if(s.remainingAttempts===0&&s.lockExpiresAt){const n=s.lockExpiresAt>1e10?s.lockExpiresAt:s.lockExpiresAt*1e3;throw new u(d.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:n,remainingAttempts:0,maxAttempts:s.maxAttempts})}if(s.remainingAttempts!=null&&s.remainingAttempts>0)throw new u(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:s.remainingAttempts,maxAttempts:s.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new u(d.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},s=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);s&&(t.lockExpiresAt=s>1e10?s:s*1e3);const n=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof n=="number"&&(t.remainingAttempts=n);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 d.AUTH_NOT_AUTHENTICATED;case-10001:return d.UNKNOWN_ERROR;case-10006:return d.GATEWAY_INTERNAL_ERROR;case-10007:return d.BROADCAST_FAILED;case-10008:return d.GATEWAY_LOCK_CONFLICT;case-10004:return d.WALLET_ALREADY_EXISTS;case-10005:return d.WALLET_NOT_FOUND;case-10011:return d.WALLET_NOT_FOUND;case-10030:return d.WALLET_INCONSISTENT_STATE;case-10010:return d.MIGRATION_FAILED;case-10012:return d.MIGRATION_BACKUP_EXISTS;case-10013:return d.WITHDRAW_FAILED;case-10033:return d.USER_NOT_FOUND;case-10036:return d.ADDRESS_LIMIT_EXCEEDED;case-10027:return d.MIGRATION_PIN_LOCKED;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.ORIGIN_NOT_ALLOWED;case-10025:return d.INVALID_APP_TYPE;case-10028:return ae.hasLockInfo(r)?d.PIN_LOCKED:d.PIN_WRONG;case-10029:return d.PIN_INVALID;case-10031:return d.PIN_LOCKED;case-10032:return d.PIN_REPEATED_PATTERN;case-10045:return d.PIN_ENCRYPTION_INVALID;case-10046:return d.PIN_POLICY_VIOLATION;case-10026:return d.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return d.PREPARE_FAILED;case-10016:return d.PREPARE_EXPIRED;case-10017:case-10018:return d.PREPARE_MISMATCH;case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10040:return d.HMAC_REQUIRED;case-10041:return d.HMAC_VERIFICATION_FAILED;default:return d.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${Ee} 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 ns{constructor(e,r,t,s=()=>{},n=()=>{},o=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=s,this.getAppName=n,this.onBridgeUnauthorized=o,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(a,l)=>e.prepare(a,l)),e.migrateWallet&&(this.migrateWallet=(a,l)=>e.migrateWallet(a,l)),e.verifyPin&&(this.verifyPin=a=>e.verifyPin(a)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(a,l)=>e.verifyRecoveryPin(a,l))}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(s=>s.address.toLowerCase()===r.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,r,t,s){return!bt(e)||!await this.innerOwnsAddress(r,t)?!1:(this.onBridgeUnauthorized(`native 가 ${s} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,r,t,s,n,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();try{const l=await a.signMessage({chainId:r,message:t,from:o,index:s,dappName:this.getAppName()});return{chainId:r,signature:l.signature,format:"hex"}}catch(l){if(!await this.recoverFromUnauthorized(l,e,o,"signMessage"))throw l}}return this.inner.signMessage(e,r,t,s,n,o)}async signTypedData(e,r,t,s,n,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();try{const l=await a.signTypedData({chainId:r,typedData:t,from:o,index:s,dappName:this.getAppName()});return{chainId:r,signature:l.signature,format:"hex"}}catch(l){if(!await this.recoverFromUnauthorized(l,e,o,"signTypedData"))throw l}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,s,n,o)}async signTransaction(e,r,t,s,n){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:s,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}catch(a){if(!await this.recoverFromUnauthorized(a,e,t.from,"signTransaction"))throw a}}return this.inner.signTransaction(e,r,t,s,n)}async sendTransaction(e,r,t,s){const n=this.shouldUseBridge();if(n!=null&&n.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await n.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 o}}if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,s)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class we{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=we.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(s=>s.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?qt:Vt;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 u(we.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=we.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new u(d.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Re).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.APP_IDENTIFIER_MISSING;case-10025:return d.INVALID_APP_TYPE;default:return d.UNKNOWN_ERROR}}}const xt="__crossx-confirm-style",U="__crossx-confirm-overlay",os={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 gt(i,e){const r=os[i],t=e==null?void 0:e[i];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary,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 as=`
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"},ar={ko:or,en:Et};function Q(i="en",e){return ar[i]??Et}function cr(i){return i==="ko"||i==="en"?i:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const ct="crossx_access_token",lt="crossx_refresh_token",dt="crossx_user_info",Re=class Re{constructor(e,r,t,s,n,o,a,l,p=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=s,this.transport=n,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=l,this.getLocale=p,this._refreshPromise=null,this._migrated=!1;const h=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${h}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${h}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${h}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${h}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new u(d.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const s=e==null?void 0:e.provider;let n="/login";s==="google"?n="/google":s==="apple"&&(n="/apple");const{oauthServiceUrl:o,legacyOauthServiceUrl:a}=this.config,l=cr(this.getLocale()),p=m=>{const w=`${m}${n}`,x=w.includes("?")?"&":"?";return`${w}${x}locale=${l}`},h=p(o),_=a?p(a):void 0;c.log(`[CROSSx] OAuth 팝업 열기 (${s||"일반"} 로그인)`),c.log(`[CROSSx] Auth URL: ${h}`);const g=await this.oauth.openAuth({authUrl:h,..._?{legacyAuthUrl:_}:{},expectedOrigin:new URL(o).origin});r=g.token,t=g.email,c.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&c.log("[CROSSx] OAuth 콜백 email:",t)}catch(s){if(c.error("[CROSSx] SignIn 에러 (OAuth 단계):",s),s instanceof u)throw s;const n=s instanceof Error?s.message:"Sign in failed";throw/팝업|popup/i.test(n)?new u(d.OAUTH_POPUP_BLOCKED,n):new u(d.AUTH_FAILED,n)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return c.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return c.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,s,n;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let l,p;try{const h=this.crypto.decodeJWT(e.idToken);p=e.provider??((t=h.firebase)==null?void 0:t.sign_in_provider);const _=((s=h.firebase)==null?void 0:s.identities)??{};l=h.email??((n=_.email)==null?void 0:n[0]),c.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",p,"email:",l??"(없음)")}catch{c.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const h=await this.crypto.verifyJWT(a);if(!h.valid)throw new u(d.AUTH_FAILED,"Access token 검증 실패");const _=h.payload;r={id:_.sub,email:_.email??l,signInProvider:p,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),c.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),c.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new u(d.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),l=o instanceof Error?o.stack:void 0,p=o instanceof Error?o.name:"UnknownError";return c.error("[CROSSx] RN Bridge 로그인 실패 — name:",p,"message:",a,"stack:",l),{success:!1,error:a||"RN Bridge login failed"}}return c.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var n,o,a,l,p;let t,s=!1;try{const{authApiUrl:h}=this.config,{accessToken:_,refreshToken:g}=await this.exchangeFirebaseToken(e,h);let m,w,x;try{const b=this.crypto.decodeJWT(e);c.log("[CROSSx] Firebase JWT 필드:",Object.keys(b).join(", ")),w=(n=b.firebase)==null?void 0:n.sign_in_provider;const E=((o=b.firebase)==null?void 0:o.identities)??{};x=b.email??((a=E.email)==null?void 0:a[0]),w==="google.com"?m=(l=E["google.com"])==null?void 0:l[0]:w==="apple.com"&&(m=(p=E["apple.com"])==null?void 0:p[0]),c.log("[CROSSx] OAuth provider sub 추출 — provider:",w,"hasProviderSub:",!!m,"email:",x??"(없음)")}catch{c.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(_){const b=this.crypto.decodeJWT(_);c.log("[CROSSx] access_token 디코딩 — sub:",b.sub,"exp:",b.exp,"필드:",Object.keys(b).join(", "));const E=await this.crypto.verifyJWT(_);if(s=E.signatureVerified??!1,!E.valid)throw c.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const A=E.payload,k=A.email??x??r;c.log("[CROSSx] email 소스 — CROSSx JWT:",A.email??"(없음)","/ Firebase JWT:",x??"(없음)","/ OAuth 콜백:",r??"(없음)","→",k??"(없음)"),t={id:A.sub,email:k,signInProvider:w,providerSub:m},this.tokenStore.set(_),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,_),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&c.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const b=this.crypto.decodeJWT(e);t={id:b.sub,email:b.email??r,signInProvider:w,providerSub:m},c.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}c.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const y=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,y),await this.clearStoredRNBridgeSession(),c.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(h){return c.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",h),{success:!1,error:h instanceof Error?h.message:"Sign in failed"}}return c.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,s)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;c.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let s;try{s=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){c.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const l=a instanceof Error?a.message:String(a);throw new u(d.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${l}`,a)}c.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",s.status);const n=s.data;this.checkResponseError(n,"RN Bridge token exchange");const o=this.extractAccessToken(n);if(!o)throw new u(d.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return c.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,s=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;c.log("[CROSSx] Firebase 토큰 교환 요청");const n=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});c.log("[CROSSx] 토큰 교환 응답 — status:",n.status);const o=n.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return c.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new u(d.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");c.log("[CROSSx] access_token 교환 성공");let l;return t||(l=this.extractRefreshToken(o)),{accessToken:a,refreshToken:l}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const n=t.data,o=n.access_token??n.token;if(typeof o=="string")return o}const s=t.access_token??t.token;if(typeof s=="string")return s}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const n=t.data,o=n.refresh_token??n.refresh;if(typeof o=="string")return o}const s=t.refresh_token??t.refresh;if(typeof s=="string")return s}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const s=await this.storage.get(this.STORAGE_KEY_USER);if(s)return c.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(s,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){c.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),s=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(c.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",s?"있음":"없음"),s){t&&this.tokenStore.set(t);const n=await this.silentRefresh(s);c.log("[CROSSx] restoreSession — silentRefresh 결과:",n?"토큰 발급 성공":"토큰 없음"),n&&this.tokenStore.set(n)}else{if(!t)return c.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return c.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;c.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(c.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;c.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return c.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof u&&e.code===d.SESSION_EXPIRED;return c.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,s=`${r}/cross-auth/social/refresh/simple`,n={};if(!t){const h=this.tokenStore.get()??"";h&&(n.access_token=h),e&&(n.refresh_token=e)}const o=await this.transport.request({url:s,method:"POST",headers:{"Content-Type":"application/json"},body:n,...t?{credentials:"include"}:{}});c.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,l=this.extractResponseErrorCode(a);if(l){const h=Re.REFRESH_RELOGIN_CODES.has(l.code);throw new u(h?d.SESSION_EXPIRED:d.AUTH_FAILED,`토큰 갱신 실패 (코드 ${l.code}): ${l.message}`)}const p=this.extractAccessToken(a);if(t&&!p){c.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!p)throw new u(d.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(p),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p);const h=this.extractRefreshToken(a);h&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,h)}return c.log("[CROSSx] silentRefresh 성공"),p}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){c.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:s}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return s?(this.tokenStore.set(s),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,s),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),c.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof u&&t.code===d.RN_NATIVE_SESSION_EXPIRED&&(c.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(c.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof u&&e.code===d.SESSION_EXPIRED?(c.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):c.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,s=!1;try{let n=await this.crypto.verifyJWT(e);if(s=n.signatureVerified??!1,!n.valid){if(!r)return c.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};c.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return c.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,n=await this.crypto.verifyJWT(e),s=n.signatureVerified??!1,!n.valid)return c.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};c.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=n.payload;c.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",s),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),c.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(n){return c.error("[CROSSx] signInWithJWT 에러:",n),{success:!1,error:n instanceof Error?n.message:"JWT sign in failed"}}return this.loadWallet(t,s)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(dt);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(ct);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const s=await this.storage.get(lt);s&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s),await this.storage.remove(dt),await this.storage.remove(ct),await this.storage.remove(lt),c.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){c.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,s=!1;try{if(typeof this.walletProvider.checkWallet=="function"){c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const n=await this.walletProvider.checkWallet();if(c.log("[CROSSx] 지갑 상태:",n),n==="migration_required")c.log("[CROSSx] migration_required → needsMigration = true"),s=!0;else if(n==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):c.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){c.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else c.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,c.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(n){if(n instanceof u&&n.code===d.MIGRATION_BACKUP_EXISTS)c.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),s=!0;else{if(n instanceof u&&(n.code===d.PROJECT_NOT_REGISTERED||n.code===d.PROJECT_ID_MISSING||n.code===d.ORIGIN_NOT_ALLOWED))throw c.error("[CROSSx] 프로젝트 설정 에러:",n.message),n;c.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",n)}}return c.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",s),{success:!0,address:t,user:e,needsMigration:s,tokenSignatureVerified:r}}};Re.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Ue=Re;class lr{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const s=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${s}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${s}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${s}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class dr{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new u(d.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");c.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return c.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class qe{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const s=new Uint8Array(r.length);for(let n=0;n<r.length;n++)s[n]=r[n]^t[n];r.fill(0),this.xorKey=t,this.encryptedBytes=s}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}const pr=3,hr=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function ur(i){return i.code===pr||/execution reverted/i.test(i.message??"")}class _r{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const s=await this.chainRegistry.getChain(t),n={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:s.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:n})).data;if(a!=null&&a.error){const{code:l,message:p}=a.error,h={method:e,chainId:t,code:l,message:p,data:a.error.data},_=ur(a.error);throw _&&typeof h.data=="string"&&hr.test(h.data)&&(h.revertData=h.data,h.selector=h.data.slice(0,10).toLowerCase()),new u(_?d.EXECUTION_REVERTED:d.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${p} (코드: ${l})`,h)}return a==null?void 0:a.result}}class xr{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(s=>s(r))}removeAllListeners(){this.listeners.clear()}}function gr(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class Y{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return c.log("[RNBridge] Bridge is ready"),!0;await new Promise(s=>setTimeout(s,50))}return c.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await Y.waitForBridgeReady(5e3)||c.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=Y.getBridge(),!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw c.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new u(d.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,c.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=gr(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const s=await this.bridge.handshake(t);if(!s.activated)throw new u(d.AUTH_FAILED,"Bridge handshake rejected by native");const n=typeof s.walletName=="string"?s.walletName.trim():"",o=n.length>0&&n.length<=64?n:void 0,a=s.provider==="google"||s.provider==="apple"?s.provider:void 0;return{isActivated:!0,absoluteTtlMs:s.absoluteTtlMs,idleTtlMs:s.idleTtlMs,protocolVersion:s.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:s.walletAddress,walletName:o,walletProvider:a}}catch(s){throw c.error("[RNBridge] Handshake failed",s),new u(d.AUTH_FAILED,"Bridge handshake failed",s)}}async requestFirebaseIdToken(){if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new u(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof u)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new u(d.USER_REJECTED,"Firebase ID token request rejected by user",e):(c.error("[RNBridge] Firebase token request failed",e),new u(d.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new u(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof u?e:(c.error("[RNBridge] Fresh Firebase token request failed",e),new u(d.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new u(d.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new u(d.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new u(d.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof u?r:(c.warn("[RNBridge] Session restore Firebase token request failed",r),new u(d.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new u(d.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}const ue={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 fr(i){const e=i.environment,r=e&&e in ue?ue[e]:null;if(!r)return null;const t=i.overrides;if(!t)return r;const s={...r};for(const[n,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(s[n]=o);return s}function ze(){try{if(typeof __CROSSX_CONFIG__<"u"){const i=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=fr(i);if(e)return e}}catch{}try{const i=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(i&&i in ue)return ue[i]}catch{}return ue.production}function At(i){let e=i.length;for(;e>0&&i.charCodeAt(e-1)===48;)e--;return i.slice(0,e)}function wr(i,e=Ke){if(!i||i==="0x0"||i==="0x")return"0";try{const r=BigInt(i);if(r===0n)return"0";const t=10n**BigInt(it),s=r/t,o=(r%t).toString().padStart(it,"0"),a=At(o).slice(0,e);return a?`${s}.${a}`:`${s}`}catch{return"?"}}function Ee(i,e,r,t=Ke){if(!(!i||i==="0x"||i==="0x0"))try{const s=BigInt(i);if(s===0n)return;const n=10n**BigInt(r),o=s/n,l=(s%n).toString().padStart(r,"0"),p=At(l.slice(0,t)),h=p?`${o}.${p}`:`${o}`;return e?`${h} ${e}`:h}catch{return}}function mr(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new u(d.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==st)throw new u(d.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${st} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function yr(i){const e=i.startsWith("0x")?i.slice(2):i;if(!/^[0-9a-fA-F]+$/.test(e))throw new u(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new u(d.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function br(i,e){const r=Sr(e);if(i==="0"){if(r!==void 0&&r!==0)throw new u(d.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=i.match(/^eip155:(\d+)$/);if(t){const s=Number(t[1]);if(r===void 0)throw new u(d.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${i})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==s)throw new u(d.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${i}, 예상값: ${s})와 일치하지 않습니다`)}}function Sr(i){if(i==null||typeof i!="object")return;const e=i.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class pe{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new u(d.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),c.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new u(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),c.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,s){var l,p;if((p=(l=this.deps).isRNBridgeMode)!=null&&p.call(l))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){c.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let n,o;this.verifyPinMutex=new Promise((h,_)=>{n=h,o=_});const a=Q(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const _=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s});if(!_)throw new u(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(_),c.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),n();return}const h=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:s,onSubmit:async _=>{this.deps.pinStore.set(_);try{return await this.deps.walletProvider.verifyPin(_)?(c.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(g){if(this.deps.pinStore.clear(),g instanceof u){if(g.code===d.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(g.code===d.PIN_INVALID)return{ok:!1,error:g.message};if(g.code===d.PIN_LOCKED)return pe.buildPinLockedResult(g,a)}throw g}}});if(!h)throw new u(d.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(h),c.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),n()}catch(h){if(h instanceof u&&(h.code===d.AUTH_NOT_AUTHENTICATED||h.code===d.AUTH_TOKEN_EXPIRED||h.code===d.SESSION_EXPIRED)&&h.code!==d.SESSION_EXPIRED){const _=Q(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:g?this.deps.maskEmail(g,_.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(h),h}throw o(h),h}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=Q(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(s){if(s instanceof u){if(t=pe.parsePinError(s,r),!t)throw s}else throw s}for(;;){c.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(s){if(s instanceof u&&(t=pe.parsePinError(s,r),t))continue;throw s}}}static parsePinError(e,r){if(e.code===d.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===d.PIN_INVALID)return{errorMessage:e.message};if(e.code===d.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=pe.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:s,...n}=t;return{ok:!1,error:s,...n}}}class vr{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,s;if((s=(t=this.deps).isRNBridgeMode)!=null&&s.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new u(d.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let n;return this.deps.walletProvider.prepare&&(n=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(n)})}}function Er(i){return i==="google"||i==="apple"}class Ar{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const s=Er(e.loginType)?{provider:e.loginType}:void 0;let n;try{n=await this.deps.executeSignIn(s)}catch(p){throw this.deps.clearAuthState(),p}if(!n.success)return this.deps.clearAuthState(),n;const o=((r=n.user)==null?void 0:r.providerSub)??null,a=((t=n.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){c.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const p=Q(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:p.session_alert_title,message:p.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,p.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(n);try{await this.deps.loadWalletAfterAuth()}catch{c.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return c.log("[CROSSx] signInAgain: 세션 복구 성공"),n}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=Q(this.deps.getLocale()??"en"),{userEmail:s}=this.deps.getSessionSnapshot(),n=s?this.deps.maskEmail(s,t.session_alert_apple_account):void 0;if(r instanceof u&&r.code===d.WITHDRAW_FAILED){if(c.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof u&&r.code===d.WALLET_NOT_FOUND){if(c.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof u)||r.code!==d.SESSION_EXPIRED)throw r;if(c.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:n})==="signout")throw this.deps.clearAuthState(),new u(d.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new u(d.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Ir{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return c.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const s=this.deps.getUserId();if(!s)return;const n=await this.fetchWalletStatus();if(c.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const o=await this.deps.walletProvider.getAddresses(s);if(o.length>0){let l,p=!1;if(r){const _=o.find(g=>g.address.toLowerCase()===r.toLowerCase());_?l=_:(l={address:r,index:0},p=!0)}else e!==void 0?l=o.find(_=>_.index===e)??o[0]:l=o[0];p?c.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",l.address):c.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address);const h=!!r&&!!t&&l.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(l.address,l.index,h?{walletName:t}:void 0);return}c.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(s,0);c.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Tr{constructor(e){this.deps=e}async handleMigrationFlow(e){var l,p;c.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(c.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return c.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let s,n=0,o=5,a=null;for(;;){n++,c.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,s?`— 이전 메시지: ${s}`:"");const h=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:s,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(h===null)return c.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;c.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),s=void 0;try{const _=await((p=(l=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:p.call(l,h,e));if(!_){c.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(_.valid){c.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const g=_.pinStatus;if(o=g.maxAttempts,n=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const m=g.lockExpiresAt*1e3,w=Math.max(1,Math.round((m-Date.now())/1e3)),x=w<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${w}초, 메시지: ${x}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,x),n=0,s="Your account lock has been lifted. You may try again."}else c.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),s="Incorrect PIN."}catch(_){if(!(_ instanceof u))throw _;if(_.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=Q(this.deps.getLocale()??"en"),m=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:m?this.deps.maskEmail(m,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),n--;continue}throw this.deps.clearAuthState(),_}if(_.code===d.MIGRATION_PIN_LOCKED){const g=_.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return c.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const m=((g==null?void 0:g.lockExpiresAt)??0)*1e3,w=Math.max(1,Math.round((m-Date.now())/1e3)),x=w<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";c.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${w}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,x),n=0,s="Your account lock has been lifted. You may try again."}else throw c.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}c.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const h=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof u&&h.code===d.MIGRATION_FAILED)return c.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(h instanceof u&&h.code===d.SESSION_EXPIRED){c.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=Q(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:g?this.deps.maskEmail(g,_.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){c.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const x=await this.deps.executeMigrate(a,e);return c.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",x.address),x}catch(x){throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",x),x}}throw this.deps.clearAuthState(),h}throw c.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}}class kr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=m=>!(m!=null&&m.trim()),s=e.nonce===void 0||e.nonce===null,n=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!s&&!n&&!o&&!a)return e;const l={...e},p=s?l.from??this.deps.getActiveAddress()??void 0:void 0;p&&c.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",p,")"),n&&c.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&c.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[h,_,g]=await Promise.all([p?this.deps.jsonRpcCall("eth_getTransactionCount",[p,"pending"],r):null,n?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(p&&(l.nonce=parseInt(h??"0x0",16),c.log("[CROSSx] nonce 결과:",l.nonce)),n&&(l.gasLimit=_,c.log("[CROSSx] estimateGas 결과:",l.gasLimit)),o){const m=g;if(m){const w=rt;l.maxFeePerGas=`0x${(BigInt(m)+BigInt(w)).toString(16)}`,l.maxPriorityFeePerGas=w,c.log("[CROSSx] Dynamic 체인 감지 — baseFee:",m,"maxFeePerGas:",l.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else l.gasPrice=qt,c.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(l.maxPriorityFeePerGas=rt,c.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),l}}class Rr{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const s=this.crypto.recoverPersonalSignSigner(e,r);if(s.toLowerCase()!==t.toLowerCase())throw c.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:s}),new u(d.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${s}`);c.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(s){if(s instanceof u)throw s;c.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",s)}}}function Nr(i){return i?i.includes("google")?"google":i.includes("apple")?"apple":i:null}class Cr{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const s={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(s.walletName=t.walletName),this.deps.emitAddressChanged(s),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e,r){var s,n,o,a,l;const t={authenticated:e.success,userId:((s=e.user)==null?void 0:s.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:Nr((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:((l=e.user)==null?void 0:l.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 Pr{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 u(d.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Or{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new u(d.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new u(d.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Dr{constructor(e){this.deps=e}async createWallet(){var s,n;const e=this.deps.getUserId();if(!e)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");c.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(c.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;c.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 u(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((n=(s=this.deps).showWalletCreated)==null?void 0:n.call(s)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),c.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof u&&r.code===d.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;c.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const s=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(s)return this.deps.setActiveWallet(s.address,0),{address:s.address,migrated:!0};throw new u(d.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function pt(i,e){const r=i.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Lr{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new u(d.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new u(d.TX_INVALID_PARAMS,"invalid param tx_hash");const s=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(s))throw new u(d.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new u(d.TX_INVALID_PARAMS,"invalid param body");const n=this.deps.getApiBaseUrl(),o=pt(n,`/v2/token-historical/${e}/${s}`),a={clientVersion:t};try{c.log("[TokenHistory] Registering tx:",e,s);const l=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});l.status!==200&&this.handleError(l.status,"register"),c.log("[TokenHistory] Successfully registered:",e,s)}catch(l){throw l instanceof u?l:new u(d.UNKNOWN_ERROR,`Failed to register token history: ${l instanceof Error?l.message:String(l)}`)}}async getTokenHistory(e){var s;const r=this.deps.getApiBaseUrl(),t=new URL(pt(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{c.log("[TokenHistory] Fetching token history");const n=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(n.status===404)throw new u(d.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return n.status!==200&&this.handleError(n.status,"fetch"),c.log("[TokenHistory] Successfully fetched history:",((s=n.data.rows)==null?void 0:s.length)??0,"items"),n.data.rows||[]}catch(n){throw n instanceof u?n:new u(d.UNKNOWN_ERROR,`Failed to fetch token history: ${n instanceof Error?n.message:String(n)}`)}}async registerHistoryFireAndForget(e,r,t,s){const n=(s==null?void 0:s.maxRetries)??3,o=(s==null?void 0:s.retryDelayMs)??2e3;for(let a=0;a<n;a++)try{await this.registerTokenHistory(e,r,t);return}catch(l){if(l instanceof u&&l.message.includes("404")&&a<n-1){c.log(`[TokenHistory] Retry ${a+1}/${n} (404 - tx not yet indexed)`),await new Promise(h=>setTimeout(h,o));continue}throw l}}handleError(e,r){const s={400:{code:d.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:d.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:d.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:d.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new u(s.code,s.message)}}function De(i,e="Apple account"){if(i.endsWith("@privaterelay.appleid.com"))return e;const r=i.indexOf("@");if(r<0)return"*".repeat(i.length||3);const t=i.substring(0,r),s=i.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${s}`:`${t[0]}${"*".repeat(t.length-1)}${s}`}const ce=class ce extends xr{constructor(e,r,t,s,n,o,a,l,p,h,_,g){var m,w;super(),this.storage=t,this.crypto=s,this.transport=n,this.oauth=o,this.walletProvider=a,this.tokenStore=l,this.pinEncryptor=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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&at(e.logger),this.confirmation=p,this.pinStore=_??new qe,this.stateManager=new Cr({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:y,walletName:b})=>{const E={address:x,index:y};b!==void 0&&(E.walletName=b),this.emit("addressChanged",E)},emitAuthChanged:({isAuthenticated:x,address:y,userId:b,source:E})=>{this.emit("authChanged",{isAuthenticated:x,address:y,userId:b,...E?{source:E}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:ce.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new pe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:De,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new vr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Ir({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,y,b)=>this.setActiveWallet(x,y,b)}),this.migrationOrchestrator=new Tr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,y)=>this.migrateWalletUseCase.execute(x,y),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:De,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new kr({getActiveAddress:()=>this.address,estimateGas:(x,y)=>this.estimateGas(x,y),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,y,b)=>this.jsonRpc.call(x,y,b)}),this.signatureVerifier=new Rr(this.crypto),this.addressResolverService=new Pr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Or({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Dr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,y)=>this.setActiveWallet(x,y),showWalletCreated:()=>{var x,y;return((y=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:y.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Lr({transport:n,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Ar({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:De}),this.chainRegistry=h,this.jsonRpc=new _r(h,n),this.signInUseCase=new Ue(this.internalConfig,t,s,o,n,a,l,void 0,()=>this._config.locale),this.signOutUseCase=new lr(this.internalConfig,t,l),this.migrateWalletUseCase=new dr(t,a),(m=a.setOnUnauthorized)==null||m.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,c.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(r){c.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;c.log("[CROSSx SDK] v2.5.0 초기화 중..."),this.confirmation.setMessages(Q(this._config.locale));try{const s=ze();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=s.legacyOauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${s.authApiUrl}/.well-known/jwks.json`);const n=this._config.persistWalletPreference!==!1?await this.storage.get(ce.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(n==null?void 0:n.index);let a=(e==null?void 0:e.preferredWalletAddress)??(n==null?void 0:n.address),l=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&c.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),l||(l=await this.signInUseCase.restoreSession()),l!=null&&l.success){this.applyAuthResult(l);const p=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),h=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(p)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,h?{walletName:h}:void 0);else try{await this.loadWalletAfterAuth(o,a,h)}catch(_){if(_ instanceof u&&_.code===d.PIN_CANCELLED)c.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(_ instanceof u&&(_.code===d.SESSION_EXPIRED||_.code===d.AUTH_NOT_AUTHENTICATED||_.code===d.USER_NOT_FOUND))c.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",_.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),l=null;else throw _}}return this.initialized=!0,c.info("[CROSSx SDK] v2.5.0 초기화 완료"),this.emit("initialized",{restored:!!(l!=null&&l.success)}),l??null}catch(s){throw new u(d.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async tryRNBridgeBootstrap(){if(!Y.isAvailable())return null;try{c.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),c.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.5.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new Y({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.5.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),c.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const s=await this._tryBridgeSessionRestore();if(s!=null&&s.success)return s}return c.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return c.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),c.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const r=this._rnBridgeService.getContext(),t=Date.now();c.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 s=Date.now(),n=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=n.walletAddress,this._rnBridgeWalletName=n.walletName,this._rnBridgeWalletProvider=n.walletProvider,c.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-s,walletAddress:n.walletAddress??"(없음)",walletName:n.walletName??"(없음)",absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs})}catch(s){return c.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",s),this._rnBridgeService=null,null}}try{const r=await this._rnBridgeService.requestFirebaseIdToken();c.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),c.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof u&&r.code===d.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),c.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):r instanceof u&&r.code===d.SESSION_EXPIRED?(c.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(c.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;c.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,c.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(this._isAuthenticatedViaRNBridge=!1,c.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return this._isAuthenticatedViaRNBridge=!1,c.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new u(d.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw c.error("[CROSSx] Bridge session restore token request failed:",e),new u(d.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return Y.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new u(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&c.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const s=await this._tryBridgeSignIn();if(s===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(s!=null&&s.success)return s}let t=e;if(!(e!=null&&e.provider)){const s=await this.confirmation.showLoginSelector({connectOtherWallets:Zt(this._config)});if(s===null)return{success:!1,error:"User cancelled login"};if(s.type==="external")throw this.emit("connectExternalWallet",{walletId:s.walletId}),new u(d.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:s.provider}}try{const s=await this.signInUseCase.execute(t);return s.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(s)),s}catch(s){throw s instanceof u?s:new u(d.AUTH_FAILED,"로그인에 실패했습니다",s)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},s=await this.signIn(t);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:a}=await this.createWallet(),l=await this.getAddresses(),p=await this.selectWalletIfMultiple(l,r);return{...s,address:(p==null?void 0:p.address)??a,needsMigration:!1,addresses:l}}const n=await this.getAddresses(),o=await this.selectWalletIfMultiple(n,r);return{...s,address:(o==null?void 0:o.address)??s.address,addresses:n}}catch(n){throw n instanceof u&&n.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>c.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),n}}async signInWithOAuthToken(e){var t,s;if(this.ensureInitialized(),this.authenticated)throw new u(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r,"external"),(s=(t=this.oauth).cancelPending)==null||s.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(n){throw n instanceof u?n:new u(d.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",n)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),l=await this.getAddresses(),p=await this.selectWalletIfMultiple(l);return{...r,address:(p==null?void 0:p.address)??a,needsMigration:!1,addresses:l}}const n=await this.getAddresses(),o=await this.selectWalletIfMultiple(n);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:n}}catch(n){throw n instanceof u&&n.code===d.PIN_CANCELLED&&(c.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>c.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),n}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new u(d.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof u?t:new u(d.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=Y.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),c.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){c.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new u(d.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof u&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof u&&t.code===d.PIN_CANCELLED||c.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),c.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof u?r:new u(d.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const s=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,s)))).address,index:s};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(s=>s.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof u?e:new u(d.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof u?r:new u(d.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=s=>{const n=s?"dark":"light";this.applyTheme(n,this._config.themeTokens??{})};r(e.matches);const t=s=>r(s.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Q(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=nr(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 } } 를 넘겨 주세요.`)),ir)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const s=Y.getBridge(),n=this._isAuthenticatedViaRNBridge||!this.authenticated;if(s!=null&&s.signMessage&&n)try{const a=await s.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:a.signature,message:r,address:this.address??""}}catch(a){if(!St(a))throw de(a,d.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),c.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new u(d.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:l=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,l,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 u?a:new u(d.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 u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new u(d.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");br(e,r);const s=await this.resolveAddress(t==null?void 0:t.index);try{const n=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:s.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:s.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,s.address)});return mr(n.signature),{chainId:e,signature:n.signature,address:s.address}}catch(n){throw n instanceof u?n:new u(d.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,n)}}async signTypedDataOffchain(e,r){return this.signTypedData(ce.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 u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const n=this.resolveNativeCurrency(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:n.symbol,nativeDecimals:n.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:s},execute:a=>this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,a)});return yr(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof u)throw o;const a=o instanceof Error?o.message:String(o);throw new u(d.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 u(d.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const s=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);s.from||(s.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const n=this.resolveNativeCurrency(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:s.from,to:s.to,value:s.value,data:s.data,gasLimit:s.gasLimit,gasPrice:s.gasPrice,maxFeePerGas:s.maxFeePerGas,maxPriorityFeePerGas:s.maxPriorityFeePerGas,nativeSymbol:n.symbol,nativeDecimals:n.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:s},execute:async h=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,s,h)).txHash;const _=await this.walletProvider.signTransaction(this.userId,e,s,t==null?void 0:t.index,h);return _.txHash??_.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),l=a===""||a==="00000000",p=a.startsWith("a9059cbb");return(l||p)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Xt).catch(h=>c.log("[TokenHistory] register failed (non-critical):",h)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof u)throw o;const a=o instanceof Error?o.message:String(o);throw new u(d.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 s=t.intervalMs??Kt,n=Vt,o=t.timeoutMs??tt,a=Date.now()+o;let l=s;for(;Date.now()<a;){const p=await this.getTransactionReceipt(e,r);if(p)return p;await new Promise(h=>setTimeout(h,l)),l=Math.min(l*2,n)}throw new u(d.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var x,y;if(this._isAuthenticatedViaRNBridge){const b=Y.getBridge();if(b!=null&&b.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(b,e,r,t)}const{intervalMs:s,timeoutMs:n,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),l=s??((x=this._config.receiptPolling)==null?void 0:x.intervalMs)??Gt,p=n??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??tt,h=this.resolveNativeCurrency(e),_=r.from??"";let g,m;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:l,timeoutMs:p}).then(b=>{g=b;const E=BigInt(b.gasUsed)*BigInt(b.effectiveGasPrice),A=r.value?BigInt(r.value):0n,k=Ee(r.value,h.symbol,h.decimals,this._config.displayDecimals),R=Ee("0x"+E.toString(16),h.symbol,h.decimals,this._config.displayDecimals),D=Ee("0x"+(A+E).toString(16),h.symbol,h.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:b.from,to:b.to??r.to,amount:k,fees:R,total:D,nativeSymbol:h.symbol,status:b.status==="0x1"?"success":"reverted"}}).catch(b=>(m=b instanceof Error?b:new Error(String(b)),{chainId:e,txHash:a,from:_,to:r.to,amount:Ee(r.value,h.symbol,h.decimals,this._config.displayDecimals),nativeSymbol:h.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:_,to:r.to},w),m)throw m;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,s){let n;try{n=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:s.dappName??this._config.appName,accountName:s.accountName,index:s.index,timeoutMs:s.timeoutMs,pollIntervalMs:s.intervalMs})}catch(o){throw de(o,d.TRANSACTION_FAILED)}return{chainId:r,txHash:n.txHash,receipt:{transactionHash:n.txHash,blockHash:n.blockHash??"",blockNumber:n.blockNumber??"",from:n.from??t.from??"",to:n.to??null,gasUsed:n.gasUsed??"0x0",effectiveGasPrice:n.effectiveGasPrice??"0x0",status:n.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 u(d.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),c.log("[CROSSx] PIN 변경 완료")}catch(s){throw s instanceof u?s:new u(d.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",s)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new u(d.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(s){if(s instanceof u&&s.code===d.EXECUTION_REVERTED)throw s;const n=s instanceof Error?s.message:String(s);throw new u(d.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${n}`,s)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new u(d.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new u(d.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof u)throw t;const s=t instanceof Error?t.message:String(t);throw new u(d.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${s}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const s=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:s,formatted:wr(s,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof u)throw t;const s=t instanceof Error?t.message:String(t);throw new u(d.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${s}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new Ve(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){c.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(s){if(s instanceof u)throw s;const n=s instanceof Error?s.message:String(s);throw new u(d.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${n}`,s)}}setActiveWallet(e,r,t){const s=this.address;this.stateManager.setActiveWallet(e,r,t),s&&e&&s.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=Y.getBridge();if(!(e!=null&&e.onEvent)){c.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){c.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){c.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,s=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(s)){c.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){c.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){c.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const n=typeof t.walletName=="string"?t.walletName.trim():"",o=n.length>0&&n.length<=64?n:void 0;this.address&&this.address.toLowerCase()===s.toLowerCase()||(c.log("[CROSSx] Native walletChanged 수신",{address:s,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(s,0,{walletName:o}),this._rnBridgeWalletAddress=s,this._rnBridgeWalletName=o)}),c.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,r){this.stateManager.applyAuthResult(e,r)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(c.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),at(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}}};ce.WALLET_PREF_KEY="wallet_preference",ce.OFFCHAIN_CHAIN_ID="0";let ye=ce;class Fr{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw c.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return c.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw c.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw c.error("Storage clear error:",e),e}}}const Ae="crossx-sdk",ht=1,z="data",se="keys",Ie="aes-primary",Mr=12;class ut{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,r)=>{const t=indexedDB.open(this.dbName,ht);t.onupgradeneeded=()=>{const s=t.result;s.objectStoreNames.contains(z)||s.createObjectStore(z),s.objectStoreNames.contains(se)||s.createObjectStore(se)},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error)})}openLegacyIfExists(){return new Promise((e,r)=>{let t=!1;const s=indexedDB.open(Ae,ht);s.onupgradeneeded=()=>{t=!0},s.onsuccess=()=>{const n=s.result;if(t){n.close(),this.deleteDB(Ae).then(()=>e(null));return}if(!n.objectStoreNames.contains(se)||!n.objectStoreNames.contains(z)){n.close(),e(null);return}e(n)},s.onerror=()=>r(s.error)})}deleteDB(e){return new Promise(r=>{const t=indexedDB.deleteDatabase(e);t.onsuccess=()=>r(),t.onerror=()=>{c.warn("[CROSSx] IndexedDB 삭제 실패:",e,t.error),r()},t.onblocked=()=>{c.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),r()}})}idbGet(e,r){return new Promise((t,s)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>s(o.error)})}idbPut(e,r,t){return new Promise((s,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>s(),a.onerror=()=>n(a.error)})}idbDelete(e,r){return new Promise((t,s)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>s(o.error)})}idbClear(e){return new Promise((r,t)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).clear();n.onsuccess=()=>r(),n.onerror=()=>t(n.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(se,Ie);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(se,Ie,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Ae)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const r=e.transaction([se,z],"readonly"),t=r.objectStore(se).get(Ie),s=await new Promise((p,h)=>{t.onsuccess=()=>p(t.result),t.onerror=()=>h(t.error)});if(!s)return e.close(),null;const n=r.objectStore(z).getAll(),o=r.objectStore(z).getAllKeys(),[a,l]=await Promise.all([new Promise((p,h)=>{n.onsuccess=()=>p(n.result),n.onerror=()=>h(n.error)}),new Promise((p,h)=>{o.onsuccess=()=>p(o.result),o.onerror=()=>h(o.error)})]);e.close(),await this.idbPut(se,Ie,s);for(let p=0;p<l.length;p++)await this.idbPut(z,String(l[p]),a[p]);return await this.deleteDB(Ae),c.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),s}catch(e){return c.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Mr);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:s}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),s=await this.encrypt(t);await this.idbPut(z,e,s)}catch(t){throw c.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(z,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return c.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(z,e)}catch(r){throw c.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(z)}catch(e){throw c.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const $r=60;class Br{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Oe.createRemoteJWKSet(new URL(e)),c.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){c.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);c.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const s=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+$r<s)return c.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:s,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return c.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:n}=await Oe.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return c.log("[CROSSx] JWT 서명 검증 성공"),{payload:n,valid:!0,signatureVerified:!0}}catch(n){if(n instanceof Error&&(n.name==="JWSSignatureVerificationFailed"||n.name==="JWTClaimValidationFailed"))return c.error("[CROSSx] JWT 서명 검증 실패:",n),{payload:t,valid:!1,signatureVerified:!1};c.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return c.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw c.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Oe.decodeJwt(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),s=new TextEncoder().encode(`Ethereum Signed Message:
7
+ ${t.length}`),n=new Uint8Array(s.length+t.length);n.set(s,0),n.set(t,s.length);const o=et.keccak_256(n),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const l=Ur(a),p=l.slice(0,32),h=l.slice(32,64),_=l[64],g=_>=27?_-27:_,x=new Wt.secp256k1.Signature(_t(p),_t(h)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),y=et.keccak_256(x);return"0x"+Ht.bytesToHex(y.slice(12))}}function Ur(i){const e=new Uint8Array(i.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(i.substring(r*2,r*2+2),16);return e}function _t(i){let e="0x";for(const r of i)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Wr=5e3;class Hr{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:s}=await this.currentKey(),n=await Gr(s,e);return`${t}.${Kr(n)}`}catch(t){if(r)throw this.keyFailedAt=Date.now(),t instanceof u?t:new u(d.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(t)});return this.keyFailedAt=Date.now(),c.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(ot/1e3)}초 후 재확인)`),e}}invalidate(){c.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(c.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.currentKey().then(()=>{},()=>{})}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<ot}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<Yt?{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,c.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=It();if(!e)throw new u(d.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:Wr}),t=jr(r.data);if(!(t!=null&&t.keyVersion)||!(t!=null&&t.publicKey))throw new u(d.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const s=qr(t.publicKey),n=await e.importKey("spki",zr(s),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:t.keyVersion,key:n}}}async function Gr(i,e){const r=It();if(!r)throw new u(d.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const t=await r.encrypt({name:"RSA-OAEP"},i,new TextEncoder().encode(e));return new Uint8Array(t)}function It(){const i=globalThis.crypto;return(i==null?void 0:i.subtle)??null}function Kr(i){return Vr(i).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const we="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Vr(i){let e="";for(let r=0;r<i.length;r+=3){const t=i[r],s=i[r+1],n=i[r+2];e+=we[t>>2],e+=we[(t&3)<<4|(s??0)>>4],e+=s===void 0?"=":we[(s&15)<<2|(n??0)>>6],e+=n===void 0?"=":we[n&63]}return e}function qr(i){const e=i.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 s=0;s<r.length;s+=4){const n=[0,1,2,3].map(o=>{const a=r[s+o];if(a==="="||a===void 0)return-1;const l=we.indexOf(a);if(l===-1)throw new u(d.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return l});t.push((n[0]&63)<<2|(n[1]&63)>>4),n[2]!==-1&&t.push((n[1]&15)<<4|(n[2]&63)>>2),n[3]!==-1&&t.push((n[2]&3)<<6|n[3]&63)}return new Uint8Array(t)}function zr(i){const e=new Uint8Array(i.length);return e.set(i),e.buffer}function jr(i){if(!i||typeof i!="object")return null;const e=i;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new u(d.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 Yr=3e4,Xr=1e3;class Jr{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const s=await this._doRequest(e);if(s.status<500||t===r)return s}catch(s){if(t===r)throw s}await new Promise(s=>setTimeout(s,Xr*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Yr);try{const s=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let n;const o=await s.text();try{n=o?JSON.parse(o):null}catch{n={_raw:o}}return{status:s.status,data:n,headers:Object.fromEntries(s.headers.entries())}}finally{clearTimeout(t)}}}const Zr=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function je(){return typeof window>"u"?void 0:window}function Qr(){const i=je();return i==null?void 0:i.__crossx}function es(i){return i==="ios"||i==="android"?i:null}function Le(){const i=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(i)?"android":/iPhone|iPad|iPod|Macintosh/i.test(i)?"ios":null}function ts(i,e){const r=o=>o.split(/[^\d]+/).filter(a=>a!=="").map(a=>Number.parseInt(a,10)),t=r(i),s=r(e),n=Math.max(t.length,s.length);for(let o=0;o<n;o+=1){const a=(t[o]??0)-(s[o]??0);if(a!==0)return a}return 0}function rs(){const i=je();if(!i)return!1;const e=i.__crossxRNBridge;return e!=null&&e.isInstalled?!0:i.__CROSSX_BRIDGE_INITIALIZED__===!0||i.__CROSSX_RN_BRIDGE_READY__===!0}function xt(){const i=typeof navigator>"u"?"":navigator.userAgent;for(const e of Zr){const r=e.exec(i);if(r)return r[1]??null}}function be(){const i=Qr();if(i!=null&&i.browser)return{version:i.version??null,platform:es(i.platform)??Le(),detectedBy:"marker"};if(rs())return{version:xt()??null,platform:Le(),detectedBy:"bridge"};const e=xt();return e!==void 0?{version:e,platform:Le(),detectedBy:"user-agent"}:null}function ss(){return be()!==null}function is(i=3e3){const e=be();return e?Promise.resolve(e):je()?new Promise(r=>{const t=Date.now(),s=setInterval(()=>{const n=be();if(n){clearInterval(s),r(n);return}Date.now()-t>=i&&(clearInterval(s),r(null))},50)}):Promise.resolve(null)}const ns=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"]),os="crossx://oauth-callback",as="2.3.2";function cs(i){return i.platform!=="ios"?!1:i.version?ts(i.version,as)<=0:!0}class oe{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(c.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,"/"),s=atob(t);return JSON.parse(s)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),s=>s.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=oe.parseJwtPayload(e),s=t.nonce,n=typeof t.iss=="string"?t.iss:"(unknown)";if(c.log("[CROSSx] nonce 검증 시작 —",{iss:n,nonceClaimType:typeof s,nonceClaimPresent:typeof s=="string"&&s!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),n.includes("securetoken.google.com")){c.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof s!="string"||s===""){c.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:n,keys:Object.keys(t)});return}if(n.includes("appleid.apple.com")){const o=await oe.sha256Hex(r);if(c.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:s.length,match:s===o}),s!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(c.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:s.length,match:s===r}),s!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");c.log("[CROSSx] nonce 검증 성공 —",{iss:n})}openAuth(e){return new Promise((r,t)=>{const s=Math.max(e.width??500,500),n=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-s)/2,a=window.screenY+(window.outerHeight-n)/2,l=oe.generateRandom16Hex(),p=oe.generateRandom16Hex(),h=be();let _=e.authUrl;h&&e.legacyAuthUrl&&cs(h)&&(_=e.legacyAuthUrl,c.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:h.version??"(unknown)",detectedBy:h.detectedBy,authUrlBase:e.legacyAuthUrl}));const g=_.includes("?")?"&":"?",m=encodeURIComponent(window.location.origin);let w=`${_}${g}state=${l}&nonce=${p}&origin=${m}`;h&&!w.includes("redirectUrl=")&&(w+=`&redirectUrl=${encodeURIComponent(os)}`,c.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:h.detectedBy,appVersion:h.version??"(unknown)",platform:h.platform??"(unknown)"})),c.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:l.length,nonceLength:p.length,authUrlBase:_});const x=window.open(w,h?"_blank":"CROSSx OAuth",`width=${s},height=${n},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const y=setTimeout(()=>{c.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),M(),t(new Error("Authentication timeout"))},300*1e3),b=10,E=30;let A=0,k=null;const R=()=>{clearInterval(D),c.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),k=setTimeout(()=>{M(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},D=setInterval(()=>{A++;try{if(!x.closed)return;if(!!h){M(),t(new u(d.USER_REJECTED,"로그인이 취소되었습니다"));return}const K=typeof document<"u"&&document.hasFocus();A<=b&&!K?R():(M(),t(new u(d.USER_REJECTED,"로그인이 취소되었습니다")))}catch{R()}},1e3),M=()=>{this.abortPending=null,clearTimeout(y),clearInterval(D),k&&clearTimeout(k),window.removeEventListener("message",P)},P=O=>{if(!ns.has(O.origin))return;M();const K=typeof O.data.status=="string",I=K?O.data.data??{}:O.data;c.log("[CROSSx] OAuth postMessage 수신 —",{format:K?"wrapped":"flat",status:K?O.data.status:"(flat)"});const L=(I==null?void 0:I.state)??O.data.state;if(!L||L!==l){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(K&&O.data.status!=="success"){c.error("[CROSSx] OAuth 실패:",I==null?void 0:I.error),t(new Error((I==null?void 0:I.error)||"Authentication failed"));return}if(!K&&(I!=null&&I.error)){c.error("[CROSSx] OAuth 실패:",I.error),t(new Error(I.error||"Authentication failed"));return}const $=I==null?void 0:I.idToken,X=I==null?void 0:I.accessToken,_e=X??$,Se=(I==null?void 0:I.email)||void 0;if(c.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!X,hasIdToken:!!$,hasEmail:!!Se}),!_e){c.error("[CROSSx] 토큰을 찾을 수 없음:",O.data),t(new Error("Token not found in response"));return}const xe={token:_e,email:Se},ie=ge=>{oe.verifyIdTokenNonce(ge,p).then(()=>r(xe)).catch(J=>{c.error("[CROSSx] nonce 검증 실패:",J),t(J instanceof Error?J:new Error("nonce verification failed"))})};X?X.split(".").length===3?ie(X):$?ie($):(c.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(xe)):$?ie($):t(new Error("Token not found in response"))};this.abortPending=O=>{M(),t(new Error(O))},window.addEventListener("message",P)})}}const fe="crossx_wallet_data",le="crossx_mock_pin_hash";class ls{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return c.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(fe)?"exists":"not_found";return c.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(fe);if(t)return t;const s={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(fe,s);const n=(r=this.pinStore)==null?void 0:r.get();return n&&(await this.storage.set(le,n),c.log("[Mock] 지갑 생성 — PIN 저장됨")),s}catch(t){throw new u(d.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(fe);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return c.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,r,t,s=0,n,o){return c.log(`[Mock] signMessage chainId=${r} index=${s} uuid=${n} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,s=0,n,o){return c.log(`[Mock] signTypedData chainId=${r} index=${s} uuid=${n} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,s=0,n){c.log(`[Mock] signTransaction chainId=${r} index=${s} uuid=${n}:`,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,s){return c.log(`[Mock] sendTransaction chainId=${r} uuid=${s}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(c.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(le);return r&&r!==e?!1:(r||await this.storage.set(le,e),(t=this.pinStore)==null||t.set(e),c.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var n;if(c.log("[Mock] changePin"),this.pinScenario==="wrong")throw new u(d.PIN_WRONG,"Incorrect PIN.");const t=(n=this.pinStore)==null?void 0:n.get(),s=await this.storage.get(le);if(s&&t&&s!==t)throw new u(d.PIN_WRONG,"Incorrect PIN.");await this.storage.set(le,r),c.log("[Mock] changePin 완료")}async migrateWallet(e,r){var n;if(c.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new u(d.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new u(d.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(fe,t);const s=(n=this.pinStore)==null?void 0:n.get();return s&&(await this.storage.set(le,s),c.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return c.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return c.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}const ds=["password","newPassword","recoveryPin"];class ae{constructor(e,r,t,s,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=s,this.pinStore=n??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(nt))return e;const r=!e||this.tokenStore.isExpiringSoon(nt);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const s=this.tokenStore.get();if(s)return s}if(r)throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return c.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(c.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 ds){const s=e[t];if(typeof s!="string"||s==="")continue;const n=await this.pinEncryptor.seal(s);n!==s&&(r||(r={...e}),r[t]=n)}return r??e}async request(e,r,t,s=!1,n=!1){var h,_,g,m;const o=await this.ensureValidToken(),a=`${this.baseUrl}${r}`,l={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId},p=await this.sealPinFields(t);try{const x=(await this.transport.request({url:a,method:e,headers:l,body:p??void 0})).data;if(x&&typeof x.code=="number"){if(x.code<0||x.code>=400){const y=x.message||x.data||"API 요청에 실패했습니다";c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:x.code,message:y,url:a,method:e});const b=ae.mapGatewayError(x.code,x.data);if(b===d.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!n))return c.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,r,t,s,!0);if(b===d.AUTH_NOT_AUTHENTICATED&&!s&&this._onTokenRefresh){if(c.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0,n);throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(b===d.USER_NOT_FOUND)throw c.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(h=this._onUnauthorized)==null||h.call(this),new u(d.USER_NOT_FOUND,ae.getGatewayErrorMessage(x.code,y));const E=b===d.AUTH_NOT_AUTHENTICATED?d.SESSION_EXPIRED:b,A=E===d.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":ae.getGatewayErrorMessage(x.code,y),k=x.data;let R;throw b===d.PIN_LOCKED?R=ae.extractLockDetails(k):b===d.ADDRESS_LIMIT_EXCEEDED?R={limit:Te,raw:k}:R=k??void 0,new u(E,A,R)}return c.log("[CROSSx] Wallet Gateway API 성공:",{code:x.code,url:a,method:e}),x.data??x}return x}catch(w){if(w instanceof u)throw w;const x=((_=w.response)==null?void 0:_.status)??w.status;if((x===401||x===403)&&!s&&this._onTokenRefresh){if(c.warn(`[CROSSx] HTTP ${x} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0,n);throw new u(d.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((g=w.response)!=null&&g.data){const y=w.response.data,b=y.message||y.data||"API 요청에 실패했습니다",E=y.code||"UNKNOWN";throw c.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:b,url:a,method:e,status:(m=w.response)==null?void 0:m.status}),new u(d.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${b}`)}throw w}}async checkWallet(){var r,t;c.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 c.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,c.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(c.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw c.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new u(d.MIGRATION_BACKUP_EXISTS,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){c.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const n=await this.getAddress(e,0);return c.log("[CROSSx] 주소 조회 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}c.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},s=await this.request("POST","/mnemonic/create",t);return c.log("[CROSSx] /mnemonic/create 완료 — address:",s.address),{id:e,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new u(d.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new u(d.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new u(d.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const s={action:e,params:t},n=await this.request("POST","/mnemonic/prepare",s);return{uuid:n.uuid,expiresAt:n.expiresAt}}async signMessage(e,r,t,s,n,o){const a={message:t,password:this.requirePin()};n&&(a.uuid=n),o&&(a.from=o);const l=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:l.signature,format:"hex"}}async signTypedData(e,r,t,s,n,o){const a={typedData:t,password:this.requirePin()};n&&(a.uuid=n),o&&(a.from=o);const l=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:l.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,s,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};n&&(o.uuid=n);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,s){const n={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return s&&(n.uuid=s),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,n)).txHash}}async migrateWallet(e,r){c.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},s=await this.request("POST","/mnemonic/migrate",t);return c.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",s.address),{id:r,address:s.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const s=t.passwordStatus;if(s.permanent)throw new u(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:s.lockExpiresAt,remainingAttempts:0,maxAttempts:s.maxAttempts});if(s.remainingAttempts===0&&s.lockExpiresAt){const n=s.lockExpiresAt>1e10?s.lockExpiresAt:s.lockExpiresAt*1e3;throw new u(d.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:n,remainingAttempts:0,maxAttempts:s.maxAttempts})}if(s.remainingAttempts!=null&&s.remainingAttempts>0)throw new u(d.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:s.remainingAttempts,maxAttempts:s.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new u(d.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},s=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);s&&(t.lockExpiresAt=s>1e10?s:s*1e3);const n=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof n=="number"&&(t.remainingAttempts=n);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 d.AUTH_NOT_AUTHENTICATED;case-10001:return d.UNKNOWN_ERROR;case-10006:return d.GATEWAY_INTERNAL_ERROR;case-10007:return d.BROADCAST_FAILED;case-10008:return d.GATEWAY_LOCK_CONFLICT;case-10004:return d.WALLET_ALREADY_EXISTS;case-10005:return d.WALLET_NOT_FOUND;case-10011:return d.WALLET_NOT_FOUND;case-10030:return d.WALLET_INCONSISTENT_STATE;case-10010:return d.MIGRATION_FAILED;case-10012:return d.MIGRATION_BACKUP_EXISTS;case-10013:return d.WITHDRAW_FAILED;case-10033:return d.USER_NOT_FOUND;case-10036:return d.ADDRESS_LIMIT_EXCEEDED;case-10027:return d.MIGRATION_PIN_LOCKED;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.ORIGIN_NOT_ALLOWED;case-10025:return d.INVALID_APP_TYPE;case-10028:return ae.hasLockInfo(r)?d.PIN_LOCKED:d.PIN_WRONG;case-10029:return d.PIN_INVALID;case-10031:return d.PIN_LOCKED;case-10032:return d.PIN_REPEATED_PATTERN;case-10045:return d.PIN_ENCRYPTION_INVALID;case-10046:return d.PIN_POLICY_VIOLATION;case-10026:return d.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return d.PREPARE_FAILED;case-10016:return d.PREPARE_EXPIRED;case-10017:case-10018:return d.PREPARE_MISMATCH;case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10040:return d.HMAC_REQUIRED;case-10041:return d.HMAC_VERIFICATION_FAILED;default:return d.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${Te} 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 ps{constructor(e,r,t,s=()=>{},n=()=>{},o=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=s,this.getAppName=n,this.onBridgeUnauthorized=o,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(a,l)=>e.prepare(a,l)),e.migrateWallet&&(this.migrateWallet=(a,l)=>e.migrateWallet(a,l)),e.verifyPin&&(this.verifyPin=a=>e.verifyPin(a)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(a,l)=>e.verifyRecoveryPin(a,l))}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(s=>s.address.toLowerCase()===r.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,r,t,s){return!St(e)||!await this.innerOwnsAddress(r,t)?!1:(this.onBridgeUnauthorized(`native 가 ${s} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,r,t,s,n,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();try{const l=await a.signMessage({chainId:r,message:t,from:o,index:s,dappName:this.getAppName()});return{chainId:r,signature:l.signature,format:"hex"}}catch(l){if(!await this.recoverFromUnauthorized(l,e,o,"signMessage"))throw de(l,d.SIGNATURE_FAILED)}}return this.inner.signMessage(e,r,t,s,n,o)}async signTypedData(e,r,t,s,n,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();try{const l=await a.signTypedData({chainId:r,typedData:t,from:o,index:s,dappName:this.getAppName()});return{chainId:r,signature:l.signature,format:"hex"}}catch(l){if(!await this.recoverFromUnauthorized(l,e,o,"signTypedData"))throw de(l,d.SIGNATURE_FAILED)}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,s,n,o)}async signTransaction(e,r,t,s,n){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:s,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}catch(a){if(!await this.recoverFromUnauthorized(a,e,t.from,"signTransaction"))throw de(a,d.SIGNATURE_FAILED)}}return this.inner.signTransaction(e,r,t,s,n)}async sendTransaction(e,r,t,s){const n=this.shouldUseBridge();if(n!=null&&n.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await n.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 de(o,d.TRANSACTION_FAILED)}}if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,s)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class me{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=me.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(s=>s.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?jt:zt;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 u(me.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=me.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new u(d.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Ce).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return d.CHAIN_NOT_SUPPORTED;case-10021:return d.INVALID_CHAIN;case-10022:return d.PROJECT_NOT_REGISTERED;case-10023:return d.PROJECT_ID_MISSING;case-10024:return d.APP_IDENTIFIER_MISSING;case-10025:return d.INVALID_APP_TYPE;default:return d.UNKNOWN_ERROR}}}const gt="__crossx-confirm-style",U="__crossx-confirm-overlay",hs={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 ft(i,e){const r=hs[i],t=e==null?void 0:e[i];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary,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 us=`
8
8
  @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&family=Sora:wght@400;600&display=swap');
9
9
 
10
10
  #${U} {
@@ -2604,27 +2604,27 @@ button.__crossx-connect-other-block:active {
2604
2604
  .__crossx-tip-overlay.--visible {
2605
2605
  display: block;
2606
2606
  }
2607
- `;function V(){let i=document.getElementById(xt);i||(i=document.createElement("style"),i.id=xt,document.head.appendChild(i)),i.textContent=as}function cs(){const i=`#${U}`,e=t=>{var s,n;(n=(s=t.target)==null?void 0:s.closest)!=null&&n.call(s,i)&&t.stopImmediatePropagation()},r=t=>{var s,n;(n=(s=t.relatedTarget)==null?void 0:s.closest)!=null&&n.call(s,i)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function q(i){const e=i.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const l=a[1].trim();i.style.setProperty("--cx-bg",l);const p=document.createElement("div");p.className="__crossx-safe-area-fill",p.style.background=l,i.appendChild(p)}}const r=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])i.addEventListener(o,r);i.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])i.addEventListener(o,r);i.addEventListener("touchmove",o=>{o.stopPropagation();let a=o.target;for(;a&&a!==i;){const l=window.getComputedStyle(a);if((l.overflowY==="auto"||l.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}o.preventDefault()},{passive:!1});const t=cs(),s=ls(i),n=i.remove.bind(i);i.remove=()=>{s(),t(),n()},document.body.appendChild(i)}function ls(i){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const s=window.innerHeight,n=e.offsetTop+e.height,o=Math.max(0,Math.round(s-n));o!==r&&(r=o,i.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),i.style.removeProperty("--cx-keyboard-inset")}}function ds(i){const e=Array.from(i.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",i.appendChild(r);let t=null;const s=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const l=o.getBoundingClientRect(),p=r.offsetWidth,h=r.offsetHeight;let _=l.right-p,g=l.top-h-6;_<8&&(_=8),g<8&&(g=l.bottom+6),r.style.left=`${_}px`,r.style.top=`${g}px`,t=o},n=()=>{r.classList.remove("--visible"),t=null};e.forEach(o=>{o.addEventListener("mouseenter",()=>s(o)),o.addEventListener("mouseleave",n),o.addEventListener("touchstart",a=>{a.stopPropagation(),t===o?n():s(o)},{passive:!0})}),i.addEventListener("touchstart",o=>{o.target.closest(".__crossx-amount-tip")||n()},{passive:!0})}const ps=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function ne(){if(ps()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const i=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=i}}function te(i){return i?i.length<=13?i:`${i.slice(0,6)}…${i.slice(-4)}`:"—"}function It(i){return i?i.length<=13?i:`${i.slice(0,6)}...${i.slice(-4)}`:"—"}function kt(i,e="ONE",r=18,t=6){if(!i||i==="0x"||i==="0x0")return null;try{const s=BigInt(i);if(s===0n)return null;const n=Ke(s,r,t);if(n==="0")return null;const o=He(s,r);return Ge(`${n} ${e}`,`${o} ${e}`)}catch{return null}}const ft={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"},je=new Map;let Fe=!1;function hs(){if(Fe||(Fe=!0,typeof fetch>"u"))return;const i=Ne().contentsBaseUrl;i&&fetch(`${i}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,s]of Object.entries(r)){const n=Number(t);!Number.isNaN(n)&&s&&je.set(n,s)}}).catch(()=>{Fe=!1})}function Tt(i){return parseInt(i.split(":")[1]??"",10)}function Rt(i){var r;const e=Tt(i);if(!isNaN(e)){const t=(r=je.get(e))==null?void 0:r.name;if(t)return t;if(ft[e])return ft[e]}return i}function Ye(i,e){var r;if(i){const t=Tt(i);if(!isNaN(t)){const s=(r=je.get(t))==null?void 0:r.nativeSymbol;if(s)return s}}return e}function He(i,e){if(i===0n)return"0";const r=10n**BigInt(e),t=i/r,n=(i%r).toString().padStart(e,"0").replace(/0+$/,"");return n?`${t}.${n}`:`${t}`}function Ge(i,e){return i===e?m(i):`<span class="__crossx-amount-tip" data-full="${m(e)}">${m(i)}</span>`}function Ke(i,e,r){if(i===0n)return"0";const t=10n**BigInt(e),s=i/t,a=(i%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${s}.${a}`:`${s}`}function $e(i){try{const e=BigInt(i),r=e/1000000000n,s=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return s?`${r}.${s}`:`${r}`}catch{return i}}function us(i){try{return BigInt(i).toLocaleString()}catch{return i}}function _s(i,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:s,maxPriorityFeePerGas:n,nativeDecimals:o=18}=i,a=Ye(i.chainId,i.nativeSymbol??"ETH");if(!r)return null;try{const l=BigInt(r),p=us(r);if(s){const h=l*BigInt(s);return{isDynamic:!0,estTxFee:Ge(`${Ke(h,o,e)} ${a}`,`${He(h,o)} ${a}`),maxFeeGwei:$e(s),maxPriorityFeeGwei:n?$e(n):void 0,gasLimitFormatted:p}}if(t){const h=l*BigInt(t);return{isDynamic:!1,estTxFee:Ge(`${Ke(h,o,e)} ${a}`,`${He(h,o)} ${a}`),gasPriceGwei:$e(t),gasLimitFormatted:p}}return{isDynamic:!1,estTxFee:`${l.toLocaleString()} gas`,gasLimitFormatted:p}}catch{return null}}function Nt(i,e,r){const t=_s(i,e);if(!t)return M((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let s=M((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(s+=M((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(s+=M((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(s+=M((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(s+=M((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),s}const ee=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2607
+ `;function V(){let i=document.getElementById(gt);i||(i=document.createElement("style"),i.id=gt,document.head.appendChild(i)),i.textContent=us}function _s(){const i=`#${U}`,e=t=>{var s,n;(n=(s=t.target)==null?void 0:s.closest)!=null&&n.call(s,i)&&t.stopImmediatePropagation()},r=t=>{var s,n;(n=(s=t.relatedTarget)==null?void 0:s.closest)!=null&&n.call(s,i)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function q(i){const e=i.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const l=a[1].trim();i.style.setProperty("--cx-bg",l);const p=document.createElement("div");p.className="__crossx-safe-area-fill",p.style.background=l,i.appendChild(p)}}const r=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])i.addEventListener(o,r);i.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])i.addEventListener(o,r);i.addEventListener("touchmove",o=>{o.stopPropagation();let a=o.target;for(;a&&a!==i;){const l=window.getComputedStyle(a);if((l.overflowY==="auto"||l.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}o.preventDefault()},{passive:!1});const t=_s(),s=xs(i),n=i.remove.bind(i);i.remove=()=>{s(),t(),n()},document.body.appendChild(i)}function xs(i){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const s=window.innerHeight,n=e.offsetTop+e.height,o=Math.max(0,Math.round(s-n));o!==r&&(r=o,i.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),i.style.removeProperty("--cx-keyboard-inset")}}function gs(i){const e=Array.from(i.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",i.appendChild(r);let t=null;const s=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const l=o.getBoundingClientRect(),p=r.offsetWidth,h=r.offsetHeight;let _=l.right-p,g=l.top-h-6;_<8&&(_=8),g<8&&(g=l.bottom+6),r.style.left=`${_}px`,r.style.top=`${g}px`,t=o},n=()=>{r.classList.remove("--visible"),t=null};e.forEach(o=>{o.addEventListener("mouseenter",()=>s(o)),o.addEventListener("mouseleave",n),o.addEventListener("touchstart",a=>{a.stopPropagation(),t===o?n():s(o)},{passive:!0})}),i.addEventListener("touchstart",o=>{o.target.closest(".__crossx-amount-tip")||n()},{passive:!0})}const fs=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function ne(){if(fs()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const i=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=i}}function te(i){return i?i.length<=13?i:`${i.slice(0,6)}…${i.slice(-4)}`:"—"}function Tt(i){return i?i.length<=13?i:`${i.slice(0,6)}...${i.slice(-4)}`:"—"}function kt(i,e="ONE",r=18,t=6){if(!i||i==="0x"||i==="0x0")return null;try{const s=BigInt(i);if(s===0n)return null;const n=Ge(s,r,t);if(n==="0")return null;const o=We(s,r);return He(`${n} ${e}`,`${o} ${e}`)}catch{return null}}const wt={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"},Ye=new Map;let Fe=!1;function ws(){if(Fe||(Fe=!0,typeof fetch>"u"))return;const i=ze().contentsBaseUrl;i&&fetch(`${i}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,s]of Object.entries(r)){const n=Number(t);!Number.isNaN(n)&&s&&Ye.set(n,s)}}).catch(()=>{Fe=!1})}function Rt(i){return parseInt(i.split(":")[1]??"",10)}function Nt(i){var r;const e=Rt(i);if(!isNaN(e)){const t=(r=Ye.get(e))==null?void 0:r.name;if(t)return t;if(wt[e])return wt[e]}return i}function Xe(i,e){var r;if(i){const t=Rt(i);if(!isNaN(t)){const s=(r=Ye.get(t))==null?void 0:r.nativeSymbol;if(s)return s}}return e}function We(i,e){if(i===0n)return"0";const r=10n**BigInt(e),t=i/r,n=(i%r).toString().padStart(e,"0").replace(/0+$/,"");return n?`${t}.${n}`:`${t}`}function He(i,e){return i===e?f(i):`<span class="__crossx-amount-tip" data-full="${f(e)}">${f(i)}</span>`}function Ge(i,e,r){if(i===0n)return"0";const t=10n**BigInt(e),s=i/t,a=(i%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${s}.${a}`:`${s}`}function Me(i){try{const e=BigInt(i),r=e/1000000000n,s=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return s?`${r}.${s}`:`${r}`}catch{return i}}function ms(i){try{return BigInt(i).toLocaleString()}catch{return i}}function ys(i,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:s,maxPriorityFeePerGas:n,nativeDecimals:o=18}=i,a=Xe(i.chainId,i.nativeSymbol??"ETH");if(!r)return null;try{const l=BigInt(r),p=ms(r);if(s){const h=l*BigInt(s);return{isDynamic:!0,estTxFee:He(`${Ge(h,o,e)} ${a}`,`${We(h,o)} ${a}`),maxFeeGwei:Me(s),maxPriorityFeeGwei:n?Me(n):void 0,gasLimitFormatted:p}}if(t){const h=l*BigInt(t);return{isDynamic:!1,estTxFee:He(`${Ge(h,o,e)} ${a}`,`${We(h,o)} ${a}`),gasPriceGwei:Me(t),gasLimitFormatted:p}}return{isDynamic:!1,estTxFee:`${l.toLocaleString()} gas`,gasLimitFormatted:p}}catch{return null}}function Ct(i,e,r){const t=ys(i,e);if(!t)return F((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let s=F((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(s+=F((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(s+=F((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(s+=F((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(s+=F((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),s}const ee=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2608
2608
  <rect x="9" y="9" width="13" height="13" rx="2"/>
2609
2609
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
2610
2610
  </svg>`,H=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2611
2611
  <line x1="18" y1="6" x2="6" y2="18"/>
2612
2612
  <line x1="6" y1="6" x2="18" y2="18"/>
2613
- </svg>`,xs='<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>',gs='<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 Pt(i,e){return`<svg width="${i}" height="${i}" 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 fs=Pt(16,"connect-inline"),ws={[pe.MetaMask]:xs,[pe.Binance]:gs,[pe.CROSSx]:fs},Ct='<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"/>',Xe=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${Ct}</svg>`,ms=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2613
+ </svg>`,bs='<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>',Ss='<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 Pt(i,e){return`<svg width="${i}" height="${i}" 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 vs=Pt(16,"connect-inline"),Es={[he.MetaMask]:bs,[he.Binance]:Ss,[he.CROSSx]:vs},Ot='<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"/>',Je=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${Ot}</svg>`,As=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2614
2614
  <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>`,ys=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2615
+ </svg>`,Is=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2616
2616
  <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
2617
2617
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
2618
2618
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
2619
- </svg>`;function G(i){return[`--cx-bg:${i.bg}`,`--cx-border:${i.border}`,`--cx-border-medium:${i.borderMedium}`,`--cx-title:${i.titleColor}`,`--cx-content-high:${i.contentHigh}`,`--cx-subtitle:${i.subtitleColor}`,`--cx-label:${i.labelColor}`,`--cx-value:${i.valueColor}`,`--cx-pill-bg:${i.pillBg}`,`--cx-pill-from:${i.pillFromColor}`,`--cx-pill-amt:${i.pillAmtColor}`,`--cx-divider:${i.divider}`,`--cx-close:${i.closeColor}`,`--cx-close-hover:${i.closeHoverBg}`,`--cx-copy:${i.copyColor}`,`--cx-input-bg:${i.inputBg}`,`--cx-input-border:${i.inputBorder}`,`--cx-hint:${i.hintColor}`,`--cx-surface-subtle:${i.surfaceSubtle}`,`--cx-surface-high:${i.surfaceHigh}`,`--cx-primary:${i.primary}`,`--cx-primary-glow:${i.primaryGlow}`,`--cx-primary-gradient:${i.primaryGradient}`,`--cx-secondary:${i.secondary}`,`--cx-error:${i.errorColor}`,`--cx-notice-bg:${i.noticeBg}`,`--cx-notice-border:${i.noticeBorder}`,`--cx-notice-title:${i.noticeTitleColor}`,`--cx-on-primary:${i.onPrimary}`].join(";")}function bs(i,e){i.style.setProperty("--cx-bg",e.bg),i.style.setProperty("--cx-border",e.border),i.style.setProperty("--cx-border-medium",e.borderMedium),i.style.setProperty("--cx-title",e.titleColor),i.style.setProperty("--cx-subtitle",e.subtitleColor),i.style.setProperty("--cx-label",e.labelColor),i.style.setProperty("--cx-value",e.valueColor),i.style.setProperty("--cx-pill-bg",e.pillBg),i.style.setProperty("--cx-pill-from",e.pillFromColor),i.style.setProperty("--cx-pill-amt",e.pillAmtColor),i.style.setProperty("--cx-divider",e.divider),i.style.setProperty("--cx-close",e.closeColor),i.style.setProperty("--cx-close-hover",e.closeHoverBg),i.style.setProperty("--cx-copy",e.copyColor),i.style.setProperty("--cx-input-bg",e.inputBg),i.style.setProperty("--cx-input-border",e.inputBorder),i.style.setProperty("--cx-hint",e.hintColor),i.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),i.style.setProperty("--cx-surface-high",e.surfaceHigh),i.style.setProperty("--cx-primary",e.primary),i.style.setProperty("--cx-primary-glow",e.primaryGlow),i.style.setProperty("--cx-primary-gradient",e.primaryGradient),i.style.setProperty("--cx-secondary",e.secondary),i.style.setProperty("--cx-error",e.errorColor),i.style.setProperty("--cx-notice-bg",e.noticeBg),i.style.setProperty("--cx-notice-border",e.noticeBorder),i.style.setProperty("--cx-notice-title",e.noticeTitleColor),i.style.setProperty("--cx-on-primary",e.onPrimary)}function M(i,e){return`
2619
+ </svg>`;function G(i){return[`--cx-bg:${i.bg}`,`--cx-border:${i.border}`,`--cx-border-medium:${i.borderMedium}`,`--cx-title:${i.titleColor}`,`--cx-content-high:${i.contentHigh}`,`--cx-subtitle:${i.subtitleColor}`,`--cx-label:${i.labelColor}`,`--cx-value:${i.valueColor}`,`--cx-pill-bg:${i.pillBg}`,`--cx-pill-from:${i.pillFromColor}`,`--cx-pill-amt:${i.pillAmtColor}`,`--cx-divider:${i.divider}`,`--cx-close:${i.closeColor}`,`--cx-close-hover:${i.closeHoverBg}`,`--cx-copy:${i.copyColor}`,`--cx-input-bg:${i.inputBg}`,`--cx-input-border:${i.inputBorder}`,`--cx-hint:${i.hintColor}`,`--cx-surface-subtle:${i.surfaceSubtle}`,`--cx-surface-high:${i.surfaceHigh}`,`--cx-primary:${i.primary}`,`--cx-primary-glow:${i.primaryGlow}`,`--cx-primary-gradient:${i.primaryGradient}`,`--cx-secondary:${i.secondary}`,`--cx-error:${i.errorColor}`,`--cx-notice-bg:${i.noticeBg}`,`--cx-notice-border:${i.noticeBorder}`,`--cx-notice-title:${i.noticeTitleColor}`,`--cx-on-primary:${i.onPrimary}`].join(";")}function Ts(i,e){i.style.setProperty("--cx-bg",e.bg),i.style.setProperty("--cx-border",e.border),i.style.setProperty("--cx-border-medium",e.borderMedium),i.style.setProperty("--cx-title",e.titleColor),i.style.setProperty("--cx-subtitle",e.subtitleColor),i.style.setProperty("--cx-label",e.labelColor),i.style.setProperty("--cx-value",e.valueColor),i.style.setProperty("--cx-pill-bg",e.pillBg),i.style.setProperty("--cx-pill-from",e.pillFromColor),i.style.setProperty("--cx-pill-amt",e.pillAmtColor),i.style.setProperty("--cx-divider",e.divider),i.style.setProperty("--cx-close",e.closeColor),i.style.setProperty("--cx-close-hover",e.closeHoverBg),i.style.setProperty("--cx-copy",e.copyColor),i.style.setProperty("--cx-input-bg",e.inputBg),i.style.setProperty("--cx-input-border",e.inputBorder),i.style.setProperty("--cx-hint",e.hintColor),i.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),i.style.setProperty("--cx-surface-high",e.surfaceHigh),i.style.setProperty("--cx-primary",e.primary),i.style.setProperty("--cx-primary-glow",e.primaryGlow),i.style.setProperty("--cx-primary-gradient",e.primaryGradient),i.style.setProperty("--cx-secondary",e.secondary),i.style.setProperty("--cx-error",e.errorColor),i.style.setProperty("--cx-notice-bg",e.noticeBg),i.style.setProperty("--cx-notice-border",e.noticeBorder),i.style.setProperty("--cx-notice-title",e.noticeTitleColor),i.style.setProperty("--cx-on-primary",e.onPrimary)}function F(i,e){return`
2620
2620
  <div class="__crossx-row">
2621
2621
  <span class="__crossx-row-label">${i}</span>
2622
2622
  <div class="__crossx-row-value">${e}</div>
2623
- </div>`}function Ss(i,e,r,t){const s=e,n=Ye(i.chainId,i.nativeSymbol??"ETH"),o=i.nativeDecimals??18,a=Pe(i.dappName),l=i.to?`<span class="__crossx-addr-text">${te(i.to)}</span>
2624
- <button class="__crossx-copy-btn" data-copy="${m(i.to)}" title="Copy address">${ee}</button>`:"<span>—</span>",p=Nt(i,r,t),h=kt(i.value,n,o,r),_=h?M((t==null?void 0:t.label_value)??"Value",`<span>${h}</span>`):"",g=i.data??"0x",w=document.createElement("div");return w.id=U,w.innerHTML=`
2623
+ </div>`}function ks(i,e,r,t){const s=e,n=Xe(i.chainId,i.nativeSymbol??"ETH"),o=i.nativeDecimals??18,a=Pe(i.dappName),l=i.to?`<span class="__crossx-addr-text">${te(i.to)}</span>
2624
+ <button class="__crossx-copy-btn" data-copy="${f(i.to)}" title="Copy address">${ee}</button>`:"<span>—</span>",p=Ct(i,r,t),h=kt(i.value,n,o,r),_=h?F((t==null?void 0:t.label_value)??"Value",`<span>${h}</span>`):"",g=i.data??"0x",m=document.createElement("div");return m.id=U,m.innerHTML=`
2625
2625
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${G(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2626
2626
  <div class="__crossx-header">
2627
- <p class="__crossx-title" id="__crossx-ttl">${m((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
2627
+ <p class="__crossx-title" id="__crossx-ttl">${f((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
2628
2628
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2629
2629
  </div>
2630
2630
  <hr class="__crossx-divider">
@@ -2632,47 +2632,47 @@ button.__crossx-connect-other-block:active {
2632
2632
  <div class="__crossx-body-cols">
2633
2633
  <div class="__crossx-col-left">
2634
2634
  <p class="__crossx-sig-subtitle">
2635
- <span class="__crossx-sig-origin">${m(a)}</span>${m((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
2635
+ <span class="__crossx-sig-origin">${f(a)}</span>${f((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
2636
2636
  </p>
2637
2637
  <div class="__crossx-addr-pill">
2638
- ${Xe}
2638
+ ${Je}
2639
2639
  <span class="__crossx-addr-pill-text">${te(i.from)}</span>
2640
2640
  </div>
2641
- <p class="__crossx-warning">${m((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2641
+ <p class="__crossx-warning">${f((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2642
2642
  </div>
2643
2643
  <hr class="__crossx-divider __crossx-divider--cols">
2644
2644
  <div class="__crossx-col-right-sign">
2645
2645
  <div class="__crossx-rows">
2646
- ${M((t==null?void 0:t.label_to)??"To",l)}
2647
- ${M((t==null?void 0:t.label_network)??"Network",`<span>${Rt(i.chainId)}</span>`)}
2646
+ ${F((t==null?void 0:t.label_to)??"To",l)}
2647
+ ${F((t==null?void 0:t.label_network)??"Network",`<span>${Nt(i.chainId)}</span>`)}
2648
2648
  ${_}
2649
2649
  ${p}
2650
2650
  </div>
2651
- <pre class="__crossx-raw-tx">${m(g)}</pre>
2651
+ <pre class="__crossx-raw-tx">${f(g)}</pre>
2652
2652
  </div>
2653
2653
  </div>
2654
2654
  <div class="__crossx-btn-row">
2655
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${m((t==null?void 0:t.cancel)??"Cancel")}</button>
2656
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${m((t==null?void 0:t.signature_sign_button)??"Sign")}</button>
2655
+ <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${f((t==null?void 0:t.cancel)??"Cancel")}</button>
2656
+ <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${f((t==null?void 0:t.signature_sign_button)??"Sign")}</button>
2657
2657
  </div>
2658
2658
  </div>
2659
2659
  </div>
2660
- `,w}const vs=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Es(i){return i?vs.has(i.slice(0,10).toLowerCase()):!1}function As(i,e,r,t){const s=e,n=Ye(i.chainId,i.nativeSymbol??"ETH"),o=i.nativeDecimals??18,a=Pe(i.dappName),l=i.to?`<span class="__crossx-addr-text">${te(i.to)}</span>
2661
- <button class="__crossx-copy-btn" data-copy="${m(i.to)}" title="Copy address">${ee}</button>`:"<span>—</span>",p=Nt(i,r,t),_=kt(i.value,n,o,r)??"—",g=Es(i.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",w=document.createElement("div");return w.id=U,w.innerHTML=`
2660
+ `,m}const Rs=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Ns(i){return i?Rs.has(i.slice(0,10).toLowerCase()):!1}function Cs(i,e,r,t){const s=e,n=Xe(i.chainId,i.nativeSymbol??"ETH"),o=i.nativeDecimals??18,a=Pe(i.dappName),l=i.to?`<span class="__crossx-addr-text">${te(i.to)}</span>
2661
+ <button class="__crossx-copy-btn" data-copy="${f(i.to)}" title="Copy address">${ee}</button>`:"<span>—</span>",p=Ct(i,r,t),_=kt(i.value,n,o,r)??"—",g=Ns(i.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",m=document.createElement("div");return m.id=U,m.innerHTML=`
2662
2662
  <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${G(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2663
2663
  <div class="__crossx-header">
2664
- <p class="__crossx-title" id="__crossx-ttl">${m((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
2664
+ <p class="__crossx-title" id="__crossx-ttl">${f((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
2665
2665
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2666
2666
  </div>
2667
2667
  <hr class="__crossx-divider">
2668
2668
  <div class="__crossx-body">
2669
2669
  <p class="__crossx-tx-subtitle">
2670
- <span class="__crossx-sig-origin">${m(a)}</span>${m((t==null?void 0:t.send_tx_permission_text)??" wants your permission to approve the following transaction.")}
2670
+ <span class="__crossx-sig-origin">${f(a)}</span>${f((t==null?void 0:t.send_tx_permission_text)??" wants your permission to approve the following transaction.")}
2671
2671
  </p>
2672
2672
  <div class="__crossx-body-cols">
2673
2673
  <div class="__crossx-rows">
2674
- ${M((t==null?void 0:t.label_to)??"To",l)}
2675
- ${M((t==null?void 0:t.label_network)??"Network",`<span>${Rt(i.chainId)}</span>`)}
2674
+ ${F((t==null?void 0:t.label_to)??"To",l)}
2675
+ ${F((t==null?void 0:t.label_network)??"Network",`<span>${Nt(i.chainId)}</span>`)}
2676
2676
  ${p}
2677
2677
  </div>
2678
2678
  <div class="__crossx-pill">
@@ -2680,19 +2680,19 @@ button.__crossx-connect-other-block:active {
2680
2680
  <span class="__crossx-pill-amount">${_}</span>
2681
2681
  </div>
2682
2682
  </div>
2683
- <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${m(g)}</button>
2683
+ <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${f(g)}</button>
2684
2684
  </div>
2685
2685
  </div>
2686
- `,w}function Pe(i){var e;if(i)return i;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function m(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Is(i){return typeof i=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(i)}function ks(i){if(typeof i=="string")return m(i);if(typeof i=="number"||typeof i=="bigint"||typeof i=="boolean")return String(i);try{return m(JSON.stringify(i))}catch{return String(i)}}function Ts(i){return i.includes(":")?i.split(":")[1]??i:i}function Rs(i){return`https://www.crossscan.io/address/${i}?tab=txs`}function Ns(i,e){return`https://explorer.crosstoken.io/${Ts(i)}/tx/${e}`}function Ot(i,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${m(e)}" target="_blank" rel="noopener noreferrer">${m(i)}</a>`}function Ie(i){return Ot(te(i),Rs(i))}function Dt(i,e){return Ot(te(e),Ns(i,e))}function Ps(i,e,r){const t=M((r==null?void 0:r.label_from)??"From",`${Ie(i.from)}
2687
- <button class="__crossx-copy-btn" data-copy="${m(i.from)}" title="Copy address">${ee}</button>`),s=i.to?M((r==null?void 0:r.label_to)??"To",`${Ie(i.to)}
2688
- <button class="__crossx-copy-btn" data-copy="${m(i.to)}" title="Copy address">${ee}</button>`):"",n=i.amount?M((r==null?void 0:r.label_transfer)??"Transfer",`<span>${m(i.amount)}</span>`):"",o=i.fees?M((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${m(i.fees)}</span>`):"",a=i.txHash?M((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${Dt(i.chainId,i.txHash)}
2689
- <button class="__crossx-copy-btn" data-copy="${m(i.txHash)}" title="Copy hash">${ee}</button>`):"",l=i.total?`<div class="__crossx-total-pill">
2690
- <span class="__crossx-total-label">${m((r==null?void 0:r.label_total)??"Total")}<br>${m((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
2691
- <span class="__crossx-total-amount">${m(i.total)}</span>
2686
+ `,m}function Pe(i){var e;if(i)return i;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function f(i){return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Ps(i){return typeof i=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(i)}function Os(i){if(typeof i=="string")return f(i);if(typeof i=="number"||typeof i=="bigint"||typeof i=="boolean")return String(i);try{return f(JSON.stringify(i))}catch{return String(i)}}function Ds(i){return i.includes(":")?i.split(":")[1]??i:i}function Ls(i){return`https://www.crossscan.io/address/${i}?tab=txs`}function Fs(i,e){return`https://explorer.crosstoken.io/${Ds(i)}/tx/${e}`}function Dt(i,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${f(e)}" target="_blank" rel="noopener noreferrer">${f(i)}</a>`}function ke(i){return Dt(te(i),Ls(i))}function Lt(i,e){return Dt(te(e),Fs(i,e))}function Ms(i,e,r){const t=F((r==null?void 0:r.label_from)??"From",`${ke(i.from)}
2687
+ <button class="__crossx-copy-btn" data-copy="${f(i.from)}" title="Copy address">${ee}</button>`),s=i.to?F((r==null?void 0:r.label_to)??"To",`${ke(i.to)}
2688
+ <button class="__crossx-copy-btn" data-copy="${f(i.to)}" title="Copy address">${ee}</button>`):"",n=i.amount?F((r==null?void 0:r.label_transfer)??"Transfer",`<span>${f(i.amount)}</span>`):"",o=i.fees?F((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${f(i.fees)}</span>`):"",a=i.txHash?F((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${Lt(i.chainId,i.txHash)}
2689
+ <button class="__crossx-copy-btn" data-copy="${f(i.txHash)}" title="Copy hash">${ee}</button>`):"",l=i.total?`<div class="__crossx-total-pill">
2690
+ <span class="__crossx-total-label">${f((r==null?void 0:r.label_total)??"Total")}<br>${f((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
2691
+ <span class="__crossx-total-amount">${f(i.total)}</span>
2692
2692
  </div>`:"",p=document.createElement("div");return p.id=U,p.innerHTML=`
2693
2693
  <div class="__crossx-card __crossx-card--migration" style="${G(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2694
2694
  <div class="__crossx-header">
2695
- <p class="__crossx-title" id="__crossx-ttl">${m((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
2695
+ <p class="__crossx-title" id="__crossx-ttl">${f((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
2696
2696
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2697
2697
  </div>
2698
2698
  <hr class="__crossx-divider">
@@ -2705,42 +2705,42 @@ button.__crossx-connect-other-block:active {
2705
2705
  ${a}
2706
2706
  </div>
2707
2707
  ${l}
2708
- <button class="__crossx-approve-btn" id="__crossx-done-btn">${m((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
2708
+ <button class="__crossx-approve-btn" id="__crossx-done-btn">${f((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
2709
2709
  </div>
2710
2710
  </div>
2711
- `,p}function Cs(i,e,r){const t=document.createElement("div");return t.id=U,t.innerHTML=`
2711
+ `,p}function $s(i,e,r){const t=document.createElement("div");return t.id=U,t.innerHTML=`
2712
2712
  <div class="__crossx-card __crossx-card--migration" style="${G(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2713
2713
  <div class="__crossx-header">
2714
- <p class="__crossx-title" id="__crossx-ttl">${m((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
2714
+ <p class="__crossx-title" id="__crossx-ttl">${f((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
2715
2715
  </div>
2716
2716
  <hr class="__crossx-divider">
2717
2717
  <div class="__crossx-body" id="__crossx-progress-body">
2718
2718
  <div class="__crossx-progress-center">
2719
2719
  <div class="__crossx-spinner"></div>
2720
- <p class="__crossx-progress-text">${m((r==null?void 0:r.tx_progress_waiting_text)??"Waiting for transaction receipt...")}</p>
2720
+ <p class="__crossx-progress-text">${f((r==null?void 0:r.tx_progress_waiting_text)??"Waiting for transaction receipt...")}</p>
2721
2721
  </div>
2722
2722
  </div>
2723
2723
  </div>
2724
- `,t}function Os(i,e,r,t){const s=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=i.querySelector("#__crossx-ttl"),a=i.querySelector(".__crossx-header");if(o){const x=n?ys:s?"":ms,y=n?(t==null?void 0:t.tx_timeout)??"Transaction timeout":s?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";x?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${x}<span>${m(y)}</span>`):o.textContent=y}if(a&&!i.querySelector("#__crossx-close-btn")){const x=document.createElement("button");x.className="__crossx-close",x.id="__crossx-close-btn",x.setAttribute("aria-label","Close"),x.innerHTML=H,a.appendChild(x)}const l=i.querySelector("#__crossx-progress-body");if(!l)return;const p=e.from?M((t==null?void 0:t.label_from)??"From",`${Ie(e.from)}
2725
- <button class="__crossx-copy-btn" data-copy="${m(e.from)}" title="Copy address">${ee}</button>`):"",h=e.to?M((t==null?void 0:t.label_to)??"To",`${Ie(e.to)}
2726
- <button class="__crossx-copy-btn" data-copy="${m(e.to)}" title="Copy address">${ee}</button>`):"",_=e.amount?M((t==null?void 0:t.label_transfer)??"Transfer",`<span>${m(e.amount)}</span>`):"",g=e.fees?M((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${m(e.fees)}</span>`):"",w=e.txHash?M((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${Dt(e.chainId,e.txHash)}
2727
- <button class="__crossx-copy-btn" data-copy="${m(e.txHash)}" title="Copy hash">${ee}</button>`):"",f=e.total?`<div class="__crossx-total-pill">
2728
- <span class="__crossx-total-label">${m((t==null?void 0:t.label_total)??"Total")}<br>${m((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
2729
- <span class="__crossx-total-amount">${m(e.total)}</span>
2724
+ `,t}function Bs(i,e,r,t){const s=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=i.querySelector("#__crossx-ttl"),a=i.querySelector(".__crossx-header");if(o){const x=n?Is:s?"":As,y=n?(t==null?void 0:t.tx_timeout)??"Transaction timeout":s?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";x?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${x}<span>${f(y)}</span>`):o.textContent=y}if(a&&!i.querySelector("#__crossx-close-btn")){const x=document.createElement("button");x.className="__crossx-close",x.id="__crossx-close-btn",x.setAttribute("aria-label","Close"),x.innerHTML=H,a.appendChild(x)}const l=i.querySelector("#__crossx-progress-body");if(!l)return;const p=e.from?F((t==null?void 0:t.label_from)??"From",`${ke(e.from)}
2725
+ <button class="__crossx-copy-btn" data-copy="${f(e.from)}" title="Copy address">${ee}</button>`):"",h=e.to?F((t==null?void 0:t.label_to)??"To",`${ke(e.to)}
2726
+ <button class="__crossx-copy-btn" data-copy="${f(e.to)}" title="Copy address">${ee}</button>`):"",_=e.amount?F((t==null?void 0:t.label_transfer)??"Transfer",`<span>${f(e.amount)}</span>`):"",g=e.fees?F((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${f(e.fees)}</span>`):"",m=e.txHash?F((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${Lt(e.chainId,e.txHash)}
2727
+ <button class="__crossx-copy-btn" data-copy="${f(e.txHash)}" title="Copy hash">${ee}</button>`):"",w=e.total?`<div class="__crossx-total-pill">
2728
+ <span class="__crossx-total-label">${f((t==null?void 0:t.label_total)??"Total")}<br>${f((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
2729
+ <span class="__crossx-total-amount">${f(e.total)}</span>
2730
2730
  </div>`:"";l.innerHTML=`
2731
2731
  <div class="__crossx-rows">
2732
2732
  ${p}
2733
2733
  ${h}
2734
2734
  ${_}
2735
2735
  ${g}
2736
- ${w}
2736
+ ${m}
2737
2737
  </div>
2738
- ${f}
2739
- <button class="__crossx-approve-btn" id="__crossx-done-btn">${m((t==null?void 0:t.tx_complete_done_button)??(s?"All Done":"Done"))}</button>
2740
- `,l.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",y=>{var E;y.stopPropagation();const b=x.dataset.copy;b&&((E=navigator.clipboard)==null||E.writeText(b).catch(()=>{}))})})}function Ds(i,e,r){const t=e,s=Pe(i.dappName),n=m(i.message),o=document.createElement("div");return o.id=U,o.innerHTML=`
2738
+ ${w}
2739
+ <button class="__crossx-approve-btn" id="__crossx-done-btn">${f((t==null?void 0:t.tx_complete_done_button)??(s?"All Done":"Done"))}</button>
2740
+ `,l.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",y=>{var E;y.stopPropagation();const b=x.dataset.copy;b&&((E=navigator.clipboard)==null||E.writeText(b).catch(()=>{}))})})}function Us(i,e,r){const t=e,s=Pe(i.dappName),n=f(i.message),o=document.createElement("div");return o.id=U,o.innerHTML=`
2741
2741
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${G(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2742
2742
  <div class="__crossx-header">
2743
- <p class="__crossx-title" id="__crossx-ttl">${m((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
2743
+ <p class="__crossx-title" id="__crossx-ttl">${f((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
2744
2744
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2745
2745
  </div>
2746
2746
  <hr class="__crossx-divider">
@@ -2748,36 +2748,36 @@ button.__crossx-connect-other-block:active {
2748
2748
  <div class="__crossx-body-cols">
2749
2749
  <div class="__crossx-col-left">
2750
2750
  <p class="__crossx-sig-subtitle">
2751
- <span class="__crossx-sig-origin">${m(s)}</span>${m((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2751
+ <span class="__crossx-sig-origin">${f(s)}</span>${f((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2752
2752
  </p>
2753
2753
  <div class="__crossx-addr-pill">
2754
- ${Xe}
2754
+ ${Je}
2755
2755
  <span class="__crossx-addr-pill-text">${te(i.from)}</span>
2756
2756
  </div>
2757
- <p class="__crossx-warning">${m((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2757
+ <p class="__crossx-warning">${f((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2758
2758
  </div>
2759
2759
  <hr class="__crossx-divider __crossx-divider--cols">
2760
2760
  <div class="__crossx-msg-raw">${n}</div>
2761
2761
  </div>
2762
2762
  <div class="__crossx-btn-row">
2763
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${m((r==null?void 0:r.cancel)??"Cancel")}</button>
2764
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${m((r==null?void 0:r.confirm)??"Confirm")}</button>
2763
+ <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${f((r==null?void 0:r.cancel)??"Cancel")}</button>
2764
+ <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${f((r==null?void 0:r.confirm)??"Confirm")}</button>
2765
2765
  </div>
2766
2766
  </div>
2767
2767
  </div>
2768
- `,o}function Ls(i,e,r){const t=e,s=Pe(i.dappName);let n={};if(typeof i.typedData=="string")try{n=JSON.parse(i.typedData)}catch{}else i.typedData&&typeof i.typedData=="object"&&(n=i.typedData);const o=n.primaryType??"—",a=n.message??{};let l=`
2768
+ `,o}function Ws(i,e,r){const t=e,s=Pe(i.dappName);let n={};if(typeof i.typedData=="string")try{n=JSON.parse(i.typedData)}catch{}else i.typedData&&typeof i.typedData=="object"&&(n=i.typedData);const o=n.primaryType??"—",a=n.message??{};let l=`
2769
2769
  <div class="__crossx-td-row">
2770
- <span class="__crossx-td-label">${m((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
2771
- <span class="__crossx-td-value">${m(o)}</span>
2772
- </div>`;for(const[h,_]of Object.entries(a)){const g=ks(_),f=Is(_)?`<span class="__crossx-addr-text">${te(_)}</span>
2773
- <button class="__crossx-copy-btn" data-copy="${m(String(_))}" title="Copy">${ee}</button>`:`<span>${g}</span>`;l+=`
2770
+ <span class="__crossx-td-label">${f((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
2771
+ <span class="__crossx-td-value">${f(o)}</span>
2772
+ </div>`;for(const[h,_]of Object.entries(a)){const g=Os(_),w=Ps(_)?`<span class="__crossx-addr-text">${te(_)}</span>
2773
+ <button class="__crossx-copy-btn" data-copy="${f(String(_))}" title="Copy">${ee}</button>`:`<span>${g}</span>`;l+=`
2774
2774
  <div class="__crossx-td-row">
2775
- <span class="__crossx-td-label">${m(h)}</span>
2776
- <div class="__crossx-td-value">${f}</div>
2775
+ <span class="__crossx-td-label">${f(h)}</span>
2776
+ <div class="__crossx-td-value">${w}</div>
2777
2777
  </div>`}const p=document.createElement("div");return p.id=U,p.innerHTML=`
2778
2778
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${G(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2779
2779
  <div class="__crossx-header">
2780
- <p class="__crossx-title" id="__crossx-ttl">${m((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
2780
+ <p class="__crossx-title" id="__crossx-ttl">${f((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
2781
2781
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2782
2782
  </div>
2783
2783
  <hr class="__crossx-divider">
@@ -2785,35 +2785,35 @@ button.__crossx-connect-other-block:active {
2785
2785
  <div class="__crossx-body-cols">
2786
2786
  <div class="__crossx-col-left">
2787
2787
  <p class="__crossx-sig-subtitle">
2788
- <span class="__crossx-sig-origin">${m(s)}</span>${m((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2788
+ <span class="__crossx-sig-origin">${f(s)}</span>${f((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2789
2789
  </p>
2790
2790
  <div class="__crossx-addr-pill">
2791
- ${Xe}
2791
+ ${Je}
2792
2792
  <span class="__crossx-addr-pill-text">${te(i.from)}</span>
2793
2793
  </div>
2794
- <p class="__crossx-warning">${m((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2794
+ <p class="__crossx-warning">${f((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2795
2795
  </div>
2796
2796
  <hr class="__crossx-divider __crossx-divider--cols">
2797
2797
  <div class="__crossx-td-rows">${l}</div>
2798
2798
  </div>
2799
2799
  <div class="__crossx-btn-row">
2800
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${m((r==null?void 0:r.cancel)??"Cancel")}</button>
2801
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${m((r==null?void 0:r.confirm)??"Confirm")}</button>
2800
+ <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${f((r==null?void 0:r.cancel)??"Cancel")}</button>
2801
+ <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${f((r==null?void 0:r.confirm)??"Confirm")}</button>
2802
2802
  </div>
2803
2803
  </div>
2804
2804
  </div>
2805
- `,p}const Ms=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2805
+ `,p}const Hs=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2806
2806
  <line x1="12" y1="5" x2="12" y2="19"/>
2807
2807
  <line x1="5" y1="12" x2="19" y2="12"/>
2808
- </svg>`,Fs='<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 Lt(i){return i.name||`Account ${i.index+1}`}function $s(){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">${Ct}</g></svg>`}const Bs=Ne().portraitBaseUrl;function Us(i,e){const r=e.replace("#","");return`${Bs}/portrait/evm/${i}.png?size=256&bg=${r}`}function Mt(i,e,r){const t=Us(i,r),n=$s().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${t}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${n}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function Ws(i,e,r,t){const s=r==null?void 0:r.toLowerCase(),n=i.map(a=>{const l=s&&a.address.toLowerCase()===s,p=l?" __crossx-wallet-item--selected":"",h=l?`<span class="__crossx-wallet-selected">${m((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${Fs}</span>`:"";return`<button class="__crossx-wallet-item${p}" data-wallet-index="${a.index}" data-wallet-address="${m(a.address)}">
2809
- ${Mt(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${m(Lt(a))}</span><span class="__crossx-wallet-addr">${It(a.address)}</span></span>${h}
2808
+ </svg>`,Gs='<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 Ft(i){return i.name||`Account ${i.index+1}`}function Ks(){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">${Ot}</g></svg>`}const Vs=ze().portraitBaseUrl;function qs(i,e){const r=e.replace("#","");return`${Vs}/portrait/evm/${encodeURIComponent(i)}.png?size=256&bg=${encodeURIComponent(r)}`}function Mt(i,e,r){const t=qs(i,r),n=Ks().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${f(t)}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${n}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function zs(i,e,r,t){const s=r==null?void 0:r.toLowerCase(),n=i.map(a=>{const l=s&&a.address.toLowerCase()===s,p=l?" __crossx-wallet-item--selected":"",h=l?`<span class="__crossx-wallet-selected">${f((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${Gs}</span>`:"";return`<button class="__crossx-wallet-item${p}" data-wallet-index="${f(String(a.index))}" data-wallet-address="${f(a.address)}">
2809
+ ${Mt(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${f(Ft(a))}</span><span class="__crossx-wallet-addr">${f(Tt(a.address))}</span></span>${h}
2810
2810
  </button>`}).join(""),o=document.createElement("div");return o.id=U,o.className="__crossx-overlay--wallet-selector",o.innerHTML=`
2811
2811
  <div class="__crossx-card __crossx-card--wallet-selector" style="${G(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2812
2812
  <div class="__crossx-header">
2813
2813
  <span class="__crossx-wallet-sheet-handle" aria-hidden="true"></span>
2814
2814
  <div class="__crossx-wallet-header-copy">
2815
- <p class="__crossx-title" id="__crossx-ttl">${m((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
2816
- <p class="__crossx-subtitle--body">${m((t==null?void 0:t.wallet_selector_description)??"Please select the wallet you previously used for this game to continue.")}</p>
2815
+ <p class="__crossx-title" id="__crossx-ttl">${f((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
2816
+ <p class="__crossx-subtitle--body">${f((t==null?void 0:t.wallet_selector_description)??"Please select the wallet you previously used for this game to continue.")}</p>
2817
2817
  </div>
2818
2818
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2819
2819
  </div>
@@ -2824,42 +2824,42 @@ button.__crossx-connect-other-block:active {
2824
2824
  ${n}
2825
2825
  </div>
2826
2826
  <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2827
- <span class="__crossx-wallet-add-icon">${Ms}</span>
2828
- <span class="__crossx-wallet-add-label">${m((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
2827
+ <span class="__crossx-wallet-add-icon">${Hs}</span>
2828
+ <span class="__crossx-wallet-add-label">${f((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
2829
2829
  </button>
2830
2830
  <p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
2831
2831
  </div>
2832
2832
  <div class="__crossx-wallet-help-section">
2833
2833
  <div class="__crossx-mig-info">
2834
- <p class="__crossx-mig-info-title">${m((t==null?void 0:t.wallet_selector_info_title)??"Why do I need to select a wallet?")}</p>
2835
- <p class="__crossx-mig-info-desc">${m((t==null?void 0:t.wallet_selector_info_desc)??"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.")}</p>
2834
+ <p class="__crossx-mig-info-title">${f((t==null?void 0:t.wallet_selector_info_title)??"Why do I need to select a wallet?")}</p>
2835
+ <p class="__crossx-mig-info-desc">${f((t==null?void 0:t.wallet_selector_info_desc)??"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.")}</p>
2836
2836
  </div>
2837
2837
  </div>
2838
2838
  </div>
2839
2839
  </div>
2840
- `,o}function Hs(i,e){const r=document.createElement("div");r.id=U;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",bs(t,i),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const s=document.createElement("div");s.className="__crossx-header";const n=document.createElement("span");n.className="__crossx-wallet-created-sheet-handle",n.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=H,s.append(n,o,a);const l=document.createElement("hr");l.className="__crossx-divider";const p=document.createElement("div");p.className="__crossx-wallet-created-body";const h=document.createElement("div");h.className="__crossx-wallet-created-hero";const _=document.createElement("span");_.className="__crossx-wallet-created-illust",_.ariaHidden="true";const g=x=>{const y=document.createElement("span");return y.className=x,y};_.append(g("__crossx-wallet-created-shadow"),g("__crossx-wallet-created-wallet"),g("__crossx-wallet-created-coin"),g("__crossx-wallet-created-burst"),g("__crossx-wallet-created-pointer"),g("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--purple"),g("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--teal"),g("__crossx-wallet-created-dot __crossx-wallet-created-dot--one"),g("__crossx-wallet-created-dot __crossx-wallet-created-dot--two")),h.appendChild(_),p.appendChild(h);const w=document.createElement("div");w.className="__crossx-wallet-created-footer";const f=document.createElement("button");return f.className="__crossx-wallet-created-btn",f.id="__crossx-wallet-created-done",f.type="button",f.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",w.appendChild(f),t.append(s,l,p,w),r.appendChild(t),r}const Gs=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2840
+ `,o}function js(i,e){const r=document.createElement("div");r.id=U;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Ts(t,i),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const s=document.createElement("div");s.className="__crossx-header";const n=document.createElement("span");n.className="__crossx-wallet-created-sheet-handle",n.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=H,s.append(n,o,a);const l=document.createElement("hr");l.className="__crossx-divider";const p=document.createElement("div");p.className="__crossx-wallet-created-body";const h=document.createElement("div");h.className="__crossx-wallet-created-hero";const _=document.createElement("span");_.className="__crossx-wallet-created-illust",_.ariaHidden="true";const g=x=>{const y=document.createElement("span");return y.className=x,y};_.append(g("__crossx-wallet-created-shadow"),g("__crossx-wallet-created-wallet"),g("__crossx-wallet-created-coin"),g("__crossx-wallet-created-burst"),g("__crossx-wallet-created-pointer"),g("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--purple"),g("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--teal"),g("__crossx-wallet-created-dot __crossx-wallet-created-dot--one"),g("__crossx-wallet-created-dot __crossx-wallet-created-dot--two")),h.appendChild(_),p.appendChild(h);const m=document.createElement("div");m.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",m.appendChild(w),t.append(s,l,p,m),r.appendChild(t),r}const Ys=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2841
2841
  <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
2842
  <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>`,Ks=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2843
+ </svg>`,Xs=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2844
2844
  <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
2845
  <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
2846
  <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
2847
  <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 Vs(i){const e=yt(i);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${ws[i]??""}</span><span class="__crossx-connect-other-wallet-name">${m(e)}</span></span>`}function qs(i){if(i.length===0)return"";const e=s=>Vs(i[s]),r="Supported wallets include ";if(i.length===1)return`${r}${e(0)}.`;if(i.length===2)return`${r}${e(0)} and ${e(1)}.`;if(i.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=i.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function zs(i,e=[],r){const t=i,s=m(String(e[0])),n=m((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
2848
+ </svg>`;function Js(i){const e=bt(i);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Es[i]??""}</span><span class="__crossx-connect-other-wallet-name">${f(e)}</span></span>`}function Zs(i){if(i.length===0)return"";const e=s=>Js(i[s]),r="Supported wallets include ";if(i.length===1)return`${r}${e(0)}.`;if(i.length===2)return`${r}${e(0)} and ${e(1)}.`;if(i.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=i.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function Qs(i,e=[],r){const t=i,s=f(String(e[0])),n=f((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
2849
2849
  <div class="__crossx-login-or-divider">
2850
2850
  <hr><span>${n}</span><hr>
2851
2851
  </div>
2852
2852
  <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${s}" aria-labelledby="__crossx-connect-other-heading">
2853
2853
  <span class="__crossx-connect-other-text">
2854
- <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${m((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">${qs(e)}</span>
2854
+ <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${f((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">${Zs(e)}</span>
2856
2856
  </span>
2857
2857
  </button>`:"",a=document.createElement("div");return a.id=U,a.innerHTML=`
2858
2858
  <div class="__crossx-card __crossx-card--migration" style="${G(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2859
2859
  <div class="__crossx-header">
2860
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;">${m((r==null?void 0:r.login_selector_title)??Te)}</p>
2862
- <p class="__crossx-subtitle">${m((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
2861
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${f((r==null?void 0:r.login_selector_title)??Ne)}</p>
2862
+ <p class="__crossx-subtitle">${f((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
2863
2863
  </div>
2864
2864
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2865
2865
  </div>
@@ -2867,42 +2867,42 @@ button.__crossx-connect-other-block:active {
2867
2867
  <div class="__crossx-body">
2868
2868
  <div class="__crossx-login-btn-row">
2869
2869
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
2870
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${Gs}</span>
2871
- <span class="__crossx-login-btn-label">${m((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
2870
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${Ys}</span>
2871
+ <span class="__crossx-login-btn-label">${f((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
2872
2872
  </button>
2873
2873
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
2874
- <span class="__crossx-login-icon">${Ks}</span>
2875
- <span class="__crossx-login-btn-label">${m((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
2874
+ <span class="__crossx-login-icon">${Xs}</span>
2875
+ <span class="__crossx-login-btn-label">${f((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
2876
2876
  </button>
2877
2877
  </div>${o}
2878
2878
  <p class="__crossx-login-terms">
2879
- ${((r==null?void 0:r.login_selector_terms_template)??"By continuing, you agree to NEXUS {tos} and consent to its {pp}").replace("{tos}",`<a class="__crossx-login-terms-link" href="https://terms.onechain.nexus/docs/terms-july-23-2026" target="_blank" rel="noopener noreferrer">${m((r==null?void 0:r.login_selector_terms_tos)??"Terms of Service")}</a>`).replace("{pp}",`<a class="__crossx-login-terms-link" href="https://terms.onechain.nexus/docs/pp-july-23-2026" target="_blank" rel="noopener noreferrer">${m((r==null?void 0:r.login_selector_terms_pp)??"Privacy Policy.")}</a>`)}
2879
+ ${((r==null?void 0:r.login_selector_terms_template)??"By continuing, you agree to NEXUS {tos} and consent to its {pp}").replace("{tos}",`<a class="__crossx-login-terms-link" href="https://terms.onechain.nexus/docs/terms-july-23-2026" target="_blank" rel="noopener noreferrer">${f((r==null?void 0:r.login_selector_terms_tos)??"Terms of Service")}</a>`).replace("{pp}",`<a class="__crossx-login-terms-link" href="https://terms.onechain.nexus/docs/pp-july-23-2026" target="_blank" rel="noopener noreferrer">${f((r==null?void 0:r.login_selector_terms_pp)??"Privacy Policy.")}</a>`)}
2880
2880
  </p>
2881
2881
  </div>
2882
2882
  </div>
2883
- `,a}function js(i,e){const r=i,t=document.createElement("div");t.id=U;const s=m(e.message).replace(/\n/g,"<br>"),n=e.email?`<div class="__crossx-session-account-card">
2884
- <p class="__crossx-session-account-label">${m(e.accountLabel)}</p>
2885
- <p class="__crossx-session-account-email">${m(e.email)}</p>
2883
+ `,a}function ei(i,e){const r=i,t=document.createElement("div");t.id=U;const s=f(e.message).replace(/\n/g,"<br>"),n=e.email?`<div class="__crossx-session-account-card">
2884
+ <p class="__crossx-session-account-label">${f(e.accountLabel)}</p>
2885
+ <p class="__crossx-session-account-email">${f(e.email)}</p>
2886
2886
  </div>`:"";return t.innerHTML=`
2887
2887
  <div class="__crossx-card __crossx-card--migration" style="${G(r)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
2888
2888
  <div class="__crossx-header">
2889
- <p class="__crossx-title" id="__crossx-session-header-title">${m(e.title)}</p>
2889
+ <p class="__crossx-title" id="__crossx-session-header-title">${f(e.title)}</p>
2890
2890
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2891
2891
  </div>
2892
2892
  <hr class="__crossx-divider">
2893
2893
  <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
2894
2894
  <div class="__crossx-session-hero">
2895
- <p class="__crossx-session-hero-title">${m(e.title)}</p>
2895
+ <p class="__crossx-session-hero-title">${f(e.title)}</p>
2896
2896
  <p class="__crossx-session-hero-message" id="__crossx-session-msg">${s}</p>
2897
2897
  </div>
2898
2898
  ${n}
2899
2899
  <div class="__crossx-btn-row">
2900
- <button class="__crossx-cancel-btn" id="__crossx-session-signout">${m(e.signOutLabel)}</button>
2901
- <button class="__crossx-confirm-btn" id="__crossx-session-signin">${m(e.signInAgainLabel)}</button>
2900
+ <button class="__crossx-cancel-btn" id="__crossx-session-signout">${f(e.signOutLabel)}</button>
2901
+ <button class="__crossx-confirm-btn" id="__crossx-session-signin">${f(e.signInAgainLabel)}</button>
2902
2902
  </div>
2903
2903
  </div>
2904
2904
  </div>
2905
- `,t}function Ys(i,e=!0){const r=i,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>`:"",s=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",n=document.createElement("div");return n.id=U,n.innerHTML=`
2905
+ `,t}function ti(i,e=!0){const r=i,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>`:"",s=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",n=document.createElement("div");return n.id=U,n.innerHTML=`
2906
2906
  <div class="__crossx-card __crossx-card--migration" style="${G(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2907
2907
  <div class="__crossx-header">
2908
2908
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
@@ -2922,7 +2922,7 @@ button.__crossx-connect-other-block:active {
2922
2922
  ${s}
2923
2923
  </div>
2924
2924
  </div>
2925
- `,n}function Xs(i,e){const r=i,{errorMessage:t,attemptCount:s,maxAttempts:n=5}=e??{},o=!!t,a=o?" --error":"",l=s!=null&&s>0?`<p class="__crossx-pin-attempt">${s}/${n}</p>`:"",p=s!=null&&s>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",h=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",_=document.createElement("div");return _.id=U,_.innerHTML=`
2925
+ `,n}function ri(i,e){const r=i,{errorMessage:t,attemptCount:s,maxAttempts:n=5}=e??{},o=!!t,a=o?" --error":"",l=s!=null&&s>0?`<p class="__crossx-pin-attempt">${s}/${n}</p>`:"",p=s!=null&&s>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",h=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",_=document.createElement("div");return _.id=U,_.innerHTML=`
2926
2926
  <div class="__crossx-card __crossx-card--migration" style="${G(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2927
2927
  <div class="__crossx-header">
2928
2928
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
@@ -2942,7 +2942,7 @@ button.__crossx-connect-other-block:active {
2942
2942
  ${h}
2943
2943
  </div>
2944
2944
  </div>
2945
- `,_}function Js(i){const e=new Date(i),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=r[e.getDay()],n=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),l=String(e.getMinutes()).padStart(2,"0");return`${s}, ${n} ${o} ${a}:${l}`}function Zs(i,e,r){const t=i,s=e<=0,n=s?null:Date.now()+e*1e3,o=n?Js(n):null,a=document.createElement("div");return a.id=U,a.innerHTML=`
2945
+ `,_}function si(i){const e=new Date(i),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=r[e.getDay()],n=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),l=String(e.getMinutes()).padStart(2,"0");return`${s}, ${n} ${o} ${a}:${l}`}function ii(i,e,r){const t=i,s=e<=0,n=s?null:Date.now()+e*1e3,o=n?si(n):null,a=document.createElement("div");return a.id=U,a.innerHTML=`
2946
2946
  <div class="__crossx-card __crossx-card--migration" style="${G(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2947
2947
  <div class="__crossx-header">
2948
2948
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
@@ -2962,16 +2962,16 @@ button.__crossx-connect-other-block:active {
2962
2962
  </div>
2963
2963
  </div>
2964
2964
  </div>
2965
- `,{overlay:a,startCountdown:p=>{if(s||!n)return()=>{};const _=setInterval(()=>{Date.now()>=n&&(clearInterval(_),p())},1e3);return()=>clearInterval(_)}}}function Qs(i){const r=[i.check1,i.check2].map((t,s)=>`
2965
+ `,{overlay:a,startCountdown:p=>{if(s||!n)return()=>{};const _=setInterval(()=>{Date.now()>=n&&(clearInterval(_),p())},1e3);return()=>clearInterval(_)}}}function ni(i){const r=[i.check1,i.check2].map((t,s)=>`
2966
2966
  <div class="__crossx-pw-notice-item" data-check-index="${s}" role="checkbox" aria-checked="false" tabindex="0">
2967
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${s}">${si}</div>
2968
- <span class="__crossx-pw-notice-item-text">${m(t)}</span>
2967
+ <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${s}">${li}</div>
2968
+ <span class="__crossx-pw-notice-item-text">${f(t)}</span>
2969
2969
  </div>
2970
2970
  `).join("");return`
2971
2971
  <div class="__crossx-header">
2972
2972
  <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
2973
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${m(i.title)}</p>
2974
- <p class="__crossx-pw-subtitle">${m(i.headerSubtitle)}</p>
2973
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${f(i.title)}</p>
2974
+ <p class="__crossx-pw-subtitle">${f(i.headerSubtitle)}</p>
2975
2975
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
2976
2976
  </div>
2977
2977
  <hr class="__crossx-divider">
@@ -2979,10 +2979,10 @@ button.__crossx-connect-other-block:active {
2979
2979
  <div class="__crossx-pw-fields __crossx-pw-fields--notice">
2980
2980
  <div class="__crossx-pw-notice-header">
2981
2981
  <div class="__crossx-pw-notice-title-row">
2982
- <span class="__crossx-pw-notice-icon">${ii}</span>
2983
- <p class="__crossx-pw-notice-title">${m(i.noticeTitle)}</p>
2982
+ <span class="__crossx-pw-notice-icon">${di}</span>
2983
+ <p class="__crossx-pw-notice-title">${f(i.noticeTitle)}</p>
2984
2984
  </div>
2985
- <p class="__crossx-pw-notice-desc">${m(i.noticeDesc)}</p>
2985
+ <p class="__crossx-pw-notice-desc">${f(i.noticeDesc)}</p>
2986
2986
  </div>
2987
2987
  <div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
2988
2988
  ${r}
@@ -2991,41 +2991,41 @@ button.__crossx-connect-other-block:active {
2991
2991
  </div>
2992
2992
  <div class="__crossx-pin6-footer">
2993
2993
  <button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
2994
- data-next-label="${m(i.nextButton)}"
2995
- data-submit-label="${m(i.submitButton)}">
2996
- ${m(i.submitButton)}
2994
+ data-next-label="${f(i.nextButton)}"
2995
+ data-submit-label="${f(i.submitButton)}">
2996
+ ${f(i.submitButton)}
2997
2997
  </button>
2998
2998
  </div>
2999
2999
  <div class="__crossx-home-indicator"></div>
3000
- `}function Be(i){const e=!!i.lockExpiresAt&&i.lockExpiresAt>Date.now(),r=i.lockExpiresAt?` data-lock-expires="${i.lockExpiresAt}"`:"",t=i.headerSubtitle?`<p class="__crossx-pin6-header-sub">${m(i.headerSubtitle)}</p>`:"",s=i.subtitle?`<p class="__crossx-pin6-subtitle">${m(i.subtitle)}</p>`:"",n=i.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${m(i.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
- ${Ft}
3000
+ `}function $e(i){const e=!!i.lockExpiresAt&&i.lockExpiresAt>Date.now(),r=i.lockExpiresAt?` data-lock-expires="${i.lockExpiresAt}"`:"",t=i.headerSubtitle?`<p class="__crossx-pin6-header-sub">${f(i.headerSubtitle)}</p>`:"",s=i.subtitle?`<p class="__crossx-pin6-subtitle">${f(i.subtitle)}</p>`:"",n=i.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${f(i.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
+ ${$t}
3002
3002
  <span id="__crossx-pin6-lock-countdown"></span>
3003
- </p>`:"",a=i.warningMessage&&i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${m(i.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',l=i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${i.attemptCount}/${i.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',p=e?" --locked":"",h=Array.from({length:6},(x,y)=>`<input class="__crossx-pin6-box${p}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-label="PIN digit ${y+1}"${e?" disabled":""}>`).join(""),_=e?" --locked":"",g=Array.from({length:6},(x,y)=>`<div class="__crossx-pin6-dot${_}" data-dot-index="${y}" aria-label="PIN digit ${y+1}"></div>`).join(""),w=e?" --disabled":"",f=`
3003
+ </p>`:"",a=i.warningMessage&&i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${f(i.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',l=i.attemptCount!=null&&i.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${i.attemptCount}/${i.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',p=e?" --locked":"",h=Array.from({length:6},(x,y)=>`<input class="__crossx-pin6-box${p}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-label="PIN digit ${y+1}"${e?" disabled":""}>`).join(""),_=e?" --locked":"",g=Array.from({length:6},(x,y)=>`<div class="__crossx-pin6-dot${_}" data-dot-index="${y}" aria-label="PIN digit ${y+1}"></div>`).join(""),m=e?" --disabled":"",w=`
3004
3004
  <div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
3005
3005
  <div class="__crossx-pin6-numpad-row">
3006
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="1">1</button>
3007
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="2">2</button>
3008
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="3">3</button>
3006
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="1">1</button>
3007
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="2">2</button>
3008
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="3">3</button>
3009
3009
  </div>
3010
3010
  <div class="__crossx-pin6-numpad-row">
3011
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="4">4</button>
3012
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="5">5</button>
3013
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="6">6</button>
3011
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="4">4</button>
3012
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="5">5</button>
3013
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="6">6</button>
3014
3014
  </div>
3015
3015
  <div class="__crossx-pin6-numpad-row">
3016
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="7">7</button>
3017
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="8">8</button>
3018
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="9">9</button>
3016
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="7">7</button>
3017
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="8">8</button>
3018
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="9">9</button>
3019
3019
  </div>
3020
3020
  <div class="__crossx-pin6-numpad-row">
3021
3021
  <button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
3022
- <button type="button" class="__crossx-pin6-numpad-key${w}" data-key="0">0</button>
3023
- <button type="button" class="__crossx-pin6-numpad-key --delete${w}" data-key="backspace" aria-label="Delete">${ri}</button>
3022
+ <button type="button" class="__crossx-pin6-numpad-key${m}" data-key="0">0</button>
3023
+ <button type="button" class="__crossx-pin6-numpad-key --delete${m}" data-key="backspace" aria-label="Delete">${ci}</button>
3024
3024
  </div>
3025
3025
  </div>`;return`
3026
3026
  <div class="__crossx-header">
3027
3027
  <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
3028
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${m(i.title)}</p>
3028
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${f(i.title)}</p>
3029
3029
  ${t}
3030
3030
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${H}</button>
3031
3031
  </div>
@@ -3043,21 +3043,21 @@ button.__crossx-connect-other-block:active {
3043
3043
  ${l}
3044
3044
  ${o}
3045
3045
  </div>
3046
- ${f}
3047
- `}function wt(i,e){const r=document.createElement("div");return r.id=U,r.innerHTML=`
3046
+ ${w}
3047
+ `}function mt(i,e){const r=document.createElement("div");return r.id=U,r.innerHTML=`
3048
3048
  <div class="__crossx-card __crossx-card--pin6" style="${G(i)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3049
3049
  ${e}
3050
3050
  </div>
3051
- `,r}function ei(i,e){if(i.length!==6)return e.tooShort;if(!/^\d+$/.test(i))return e.numbersOnly;if(/(.)\1{2}/.test(i))return e.repeatingDigit;const r=i.split("").map(Number),t=r.every((n,o)=>o===0||n===(r[o-1]+1)%10),s=r.every((n,o)=>o===0||n===(r[o-1]+9)%10);return t||s?e.sequential:i[0]!==i[1]&&i===i.slice(0,2).repeat(3)?e.alternatingPattern:null}function ti(i){const e=Math.max(0,Math.ceil(i/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),s=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(s).padStart(2,"0")}`}function Ue(i,e,r,t,s,n,o){var Je,Ze;let a=!!(n&&n>Date.now()),l=!1;const p=()=>Array.from(i.querySelectorAll(".__crossx-pin6-box")),h=()=>i.querySelector("#__crossx-pin6-boxes"),_=()=>i.querySelector("#__crossx-pin6-error"),g=()=>i.querySelector("#__crossx-pin6-lock-msg"),w=()=>i.querySelector("#__crossx-pin6-lock-countdown"),f=()=>i.querySelector(".__crossx-pin6-body"),x="●",y=(S,v)=>{S.dataset.digit=v,S.value=x},b=S=>{delete S.dataset.digit,S.value=""},E=S=>S.dataset.digit??"",A=()=>p().map(E).join(""),T=()=>Array.from(i.querySelectorAll(".__crossx-pin6-dot")),R=()=>{var k;const S=p(),v=T();if(v.length&&(v.forEach((N,P)=>{const B=!!(S[P]&&E(S[P]));N.classList.toggle("--filled",B),N.classList.toggle("--active",!1)}),!a&&!l)){const N=S.findIndex(B=>!E(B));(k=v[N===-1?5:N])==null||k.classList.add("--active")}},D=()=>{i.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(v=>v.classList.toggle("--disabled",a)),T().forEach(v=>v.classList.toggle("--locked",a)),R()},F=S=>{a=S,p().forEach(v=>{v.disabled=S,v.classList.toggle("--locked",S)})},C=()=>i.querySelector("#__crossx-pin6-attempt"),O=()=>{const S=_();S&&(S.textContent="")},K=()=>o??"Your account will be locked after further failures.",I=()=>i.querySelector("#__crossx-pin6-warning"),L=S=>{var k;let v=I();if(!v){v=document.createElement("p"),v.className="__crossx-pin6-warning",v.id="__crossx-pin6-warning";const N=_();N?N.insertAdjacentElement("afterend",v):(k=f())==null||k.appendChild(v)}v.textContent=S},$=()=>{const S=I();S&&(S.textContent="")},X=(S,v)=>{var N;let k=C();if(!k){k=document.createElement("p"),k.className="__crossx-pin6-attempt",k.id="__crossx-pin6-attempt";const P=I()??_();P?P.insertAdjacentElement("afterend",k):(N=f())==null||N.appendChild(k)}k.textContent=`${S}/${v}`},ue=()=>{const S=C();S&&(S.textContent="")},ye=S=>{const v=_();v&&(v.textContent=S);const k=h();k==null||k.classList.add("--shake"),setTimeout(()=>k==null?void 0:k.classList.remove("--shake"),500),p().forEach(b),setTimeout(()=>{var N;(N=p()[0])==null||N.focus(),R()},50)},_e=S=>{var B;F(!0),p().forEach(b),D();const v=_();if(v&&(v.textContent="Too many failed attempts. Please wait."),!g()){const W=document.createElement("p");W.className="__crossx-pin6-lock-msg",W.id="__crossx-pin6-lock-msg",W.innerHTML=`${Ft}<span id="__crossx-pin6-lock-countdown"></span>`;const z=_();z?z.insertAdjacentElement("afterend",W):(B=f())==null||B.appendChild(W)}const k=()=>{var re;const W=S-Date.now(),z=w();W<=0?(clearInterval(N),F(!1),(re=g())==null||re.remove(),v&&(v.textContent=""),D(),setTimeout(()=>{var be;return(be=p()[0])==null?void 0:be.focus()},50)):z&&(z.textContent=` ${ti(W)}`)},N=setInterval(k,1e3);k();const P=new MutationObserver(()=>{document.contains(i)||(clearInterval(N),P.disconnect())});P.observe(document.body,{childList:!0,subtree:!1})},se=async()=>{if(a||l)return;const S=A();if(S.length===6){l=!0,p().forEach(v=>{v.disabled=!0});try{if(s){const v=await s(S);v.ok?e(S):v.lockExpiresAt?(ue(),_e(v.lockExpiresAt)):(ye(v.error??"Incorrect PIN. Please try again."),v.attemptCount!=null&&v.maxAttempts!=null?(L(K()),X(v.attemptCount,v.maxAttempts)):($(),ue()))}else e(S)}catch(v){t&&t(v)}finally{l=!1,a||p().forEach(v=>{v.disabled=!1}),R()}}};n&&n>Date.now()?_e(n):setTimeout(()=>{var S;return(S=p()[0])==null?void 0:S.focus()},100);const xe=()=>{if(a||l)return;const S=p(),v=S.find(k=>!E(k))??S[S.length-1];v==null||v.focus()};(Je=h())==null||Je.addEventListener("click",S=>{S.target.classList.contains("__crossx-pin6-box")||xe()}),(Ze=f())==null||Ze.addEventListener("click",S=>{const v=S.target;v.classList.contains("__crossx-pin6-box")||v.closest("button")||xe()}),p().forEach((S,v)=>{S.addEventListener("input",()=>{var N;const k=S.value.replace(/\D/g,"").slice(-1);k?y(S,k):b(S),O(),k&&v<5&&((N=p()[v+1])==null||N.focus()),R(),A().length===6&&setTimeout(se,80)}),S.addEventListener("keydown",k=>{var N,P;if(k.key==="Backspace"){if(k.preventDefault(),E(S))b(S);else if(v>0){const B=p()[v-1];b(B),B.focus()}R()}else k.key==="ArrowLeft"&&v>0?(k.preventDefault(),(N=p()[v-1])==null||N.focus()):k.key==="ArrowRight"&&v<5?(k.preventDefault(),(P=p()[v+1])==null||P.focus()):k.key==="Escape"&&r()}),S.addEventListener("paste",k=>{var B,W;k.preventDefault();const N=(((B=k.clipboardData)==null?void 0:B.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!N)return;const P=p();N.split("").forEach((z,re)=>{P[re]&&y(P[re],z)}),(W=P[Math.min(N.length-1,5)])==null||W.focus(),O(),R(),A().length===6&&setTimeout(se,80)}),S.addEventListener("focus",()=>S.select())});const J=i.querySelector("#__crossx-pin6-numpad");if(J){let S=null;const v=()=>{S&&(S.classList.remove("--pressed"),S=null)};J.addEventListener("pointerdown",N=>{const P=N.target.closest(".__crossx-pin6-numpad-key");!P||a||l||(v(),S=P,P.classList.add("--pressed"),P.setPointerCapture(N.pointerId))});const k=N=>{const P=N.dataset.key;if(!P)return;if(P==="backspace"){const re=[...p()].reverse().find(be=>E(be));re&&(b(re),O()),R();return}if(!/^\d$/.test(P))return;const W=p().find(z=>!E(z));W&&(y(W,P),O(),R(),A().length===6&&setTimeout(se,80))};J.addEventListener("pointerup",N=>{if(!S)return;const P=S;v();const B=P.getBoundingClientRect();N.clientX>=B.left&&N.clientX<=B.right&&N.clientY>=B.top&&N.clientY<=B.bottom&&!a&&!l&&k(P)}),J.addEventListener("pointercancel",v),J.addEventListener("pointerleave",v,!0),R(),n&&n>Date.now()&&D()}}const ri=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3051
+ `,r}function oi(i,e){if(i.length!==6)return e.tooShort;if(!/^\d+$/.test(i))return e.numbersOnly;if(/(.)\1{2}/.test(i))return e.repeatingDigit;const r=i.split("").map(Number),t=r.every((n,o)=>o===0||n===(r[o-1]+1)%10),s=r.every((n,o)=>o===0||n===(r[o-1]+9)%10);return t||s?e.sequential:i[0]!==i[1]&&i===i.slice(0,2).repeat(3)?e.alternatingPattern:null}function ai(i){const e=Math.max(0,Math.ceil(i/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),s=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(s).padStart(2,"0")}`}function Be(i,e,r,t,s,n,o){var Ze,Qe;let a=!!(n&&n>Date.now()),l=!1;const p=()=>Array.from(i.querySelectorAll(".__crossx-pin6-box")),h=()=>i.querySelector("#__crossx-pin6-boxes"),_=()=>i.querySelector("#__crossx-pin6-error"),g=()=>i.querySelector("#__crossx-pin6-lock-msg"),m=()=>i.querySelector("#__crossx-pin6-lock-countdown"),w=()=>i.querySelector(".__crossx-pin6-body"),x="●",y=(S,v)=>{S.dataset.digit=v,S.value=x},b=S=>{delete S.dataset.digit,S.value=""},E=S=>S.dataset.digit??"",A=()=>p().map(E).join(""),k=()=>Array.from(i.querySelectorAll(".__crossx-pin6-dot")),R=()=>{var T;const S=p(),v=k();if(v.length&&(v.forEach((N,C)=>{const B=!!(S[C]&&E(S[C]));N.classList.toggle("--filled",B),N.classList.toggle("--active",!1)}),!a&&!l)){const N=S.findIndex(B=>!E(B));(T=v[N===-1?5:N])==null||T.classList.add("--active")}},D=()=>{i.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(v=>v.classList.toggle("--disabled",a)),k().forEach(v=>v.classList.toggle("--locked",a)),R()},M=S=>{a=S,p().forEach(v=>{v.disabled=S,v.classList.toggle("--locked",S)})},P=()=>i.querySelector("#__crossx-pin6-attempt"),O=()=>{const S=_();S&&(S.textContent="")},K=()=>o??"Your account will be locked after further failures.",I=()=>i.querySelector("#__crossx-pin6-warning"),L=S=>{var T;let v=I();if(!v){v=document.createElement("p"),v.className="__crossx-pin6-warning",v.id="__crossx-pin6-warning";const N=_();N?N.insertAdjacentElement("afterend",v):(T=w())==null||T.appendChild(v)}v.textContent=S},$=()=>{const S=I();S&&(S.textContent="")},X=(S,v)=>{var N;let T=P();if(!T){T=document.createElement("p"),T.className="__crossx-pin6-attempt",T.id="__crossx-pin6-attempt";const C=I()??_();C?C.insertAdjacentElement("afterend",T):(N=w())==null||N.appendChild(T)}T.textContent=`${S}/${v}`},_e=()=>{const S=P();S&&(S.textContent="")},Se=S=>{const v=_();v&&(v.textContent=S);const T=h();T==null||T.classList.add("--shake"),setTimeout(()=>T==null?void 0:T.classList.remove("--shake"),500),p().forEach(b),setTimeout(()=>{var N;(N=p()[0])==null||N.focus(),R()},50)},xe=S=>{var B;M(!0),p().forEach(b),D();const v=_();if(v&&(v.textContent="Too many failed attempts. Please wait."),!g()){const W=document.createElement("p");W.className="__crossx-pin6-lock-msg",W.id="__crossx-pin6-lock-msg",W.innerHTML=`${$t}<span id="__crossx-pin6-lock-countdown"></span>`;const j=_();j?j.insertAdjacentElement("afterend",W):(B=w())==null||B.appendChild(W)}const T=()=>{var re;const W=S-Date.now(),j=m();W<=0?(clearInterval(N),M(!1),(re=g())==null||re.remove(),v&&(v.textContent=""),D(),setTimeout(()=>{var ve;return(ve=p()[0])==null?void 0:ve.focus()},50)):j&&(j.textContent=` ${ai(W)}`)},N=setInterval(T,1e3);T();const C=new MutationObserver(()=>{document.contains(i)||(clearInterval(N),C.disconnect())});C.observe(document.body,{childList:!0,subtree:!1})},ie=async()=>{if(a||l)return;const S=A();if(S.length===6){l=!0,p().forEach(v=>{v.disabled=!0});try{if(s){const v=await s(S);v.ok?e(S):v.lockExpiresAt?(_e(),xe(v.lockExpiresAt)):(Se(v.error??"Incorrect PIN. Please try again."),v.attemptCount!=null&&v.maxAttempts!=null?(L(K()),X(v.attemptCount,v.maxAttempts)):($(),_e()))}else e(S)}catch(v){t&&t(v)}finally{l=!1,a||p().forEach(v=>{v.disabled=!1}),R()}}};n&&n>Date.now()?xe(n):setTimeout(()=>{var S;return(S=p()[0])==null?void 0:S.focus()},100);const ge=()=>{if(a||l)return;const S=p(),v=S.find(T=>!E(T))??S[S.length-1];v==null||v.focus()};(Ze=h())==null||Ze.addEventListener("click",S=>{S.target.classList.contains("__crossx-pin6-box")||ge()}),(Qe=w())==null||Qe.addEventListener("click",S=>{const v=S.target;v.classList.contains("__crossx-pin6-box")||v.closest("button")||ge()}),p().forEach((S,v)=>{S.addEventListener("input",()=>{var N;const T=S.value.replace(/\D/g,"").slice(-1);T?y(S,T):b(S),O(),T&&v<5&&((N=p()[v+1])==null||N.focus()),R(),A().length===6&&setTimeout(ie,80)}),S.addEventListener("keydown",T=>{var N,C;if(T.key==="Backspace"){if(T.preventDefault(),E(S))b(S);else if(v>0){const B=p()[v-1];b(B),B.focus()}R()}else T.key==="ArrowLeft"&&v>0?(T.preventDefault(),(N=p()[v-1])==null||N.focus()):T.key==="ArrowRight"&&v<5?(T.preventDefault(),(C=p()[v+1])==null||C.focus()):T.key==="Escape"&&r()}),S.addEventListener("paste",T=>{var B,W;T.preventDefault();const N=(((B=T.clipboardData)==null?void 0:B.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!N)return;const C=p();N.split("").forEach((j,re)=>{C[re]&&y(C[re],j)}),(W=C[Math.min(N.length-1,5)])==null||W.focus(),O(),R(),A().length===6&&setTimeout(ie,80)}),S.addEventListener("focus",()=>S.select())});const J=i.querySelector("#__crossx-pin6-numpad");if(J){let S=null;const v=()=>{S&&(S.classList.remove("--pressed"),S=null)};J.addEventListener("pointerdown",N=>{const C=N.target.closest(".__crossx-pin6-numpad-key");!C||a||l||(v(),S=C,C.classList.add("--pressed"),C.setPointerCapture(N.pointerId))});const T=N=>{const C=N.dataset.key;if(!C)return;if(C==="backspace"){const re=[...p()].reverse().find(ve=>E(ve));re&&(b(re),O()),R();return}if(!/^\d$/.test(C))return;const W=p().find(j=>!E(j));W&&(y(W,C),O(),R(),A().length===6&&setTimeout(ie,80))};J.addEventListener("pointerup",N=>{if(!S)return;const C=S;v();const B=C.getBoundingClientRect();N.clientX>=B.left&&N.clientX<=B.right&&N.clientY>=B.top&&N.clientY<=B.bottom&&!a&&!l&&T(C)}),J.addEventListener("pointercancel",v),J.addEventListener("pointerleave",v,!0),R(),n&&n>Date.now()&&D()}}const ci=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3052
3052
  <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
3053
  <line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3054
3054
  <line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3055
- </svg>`,Ft=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3055
+ </svg>`,$t=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3056
3056
  <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>`,si=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3057
+ </svg>`,li=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3058
3058
  <path d="M1 4.5L4 7.5L10 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
3059
- </svg>`,ii=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3059
+ </svg>`,di=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3060
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 ni(i,e,r){var n;const t=i.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const l=o.value.replace(/\D/g,"");o.value=l?l[0]:"",l&&a<3&&t[a+1].focus();const p=Array.from(t).map(h=>h.value).join("");p.length===4&&setTimeout(()=>e(p),200)}),o.addEventListener("keydown",l=>{l.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),l.key==="Escape"&&r()}),o.addEventListener("keypress",l=>{/[0-9]/.test(l.key)||l.preventDefault()}),o.addEventListener("paste",l=>{var _;l.preventDefault();const p=(((_=l.clipboardData)==null?void 0:_.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!p)return;p.split("").forEach((g,w)=>{t[w]&&(t[w].value=g)});const h=Math.min(p.length,3);t[h].focus(),p.length===4&&setTimeout(()=>e(p),200)})});const s=i.querySelector(".__crossx-pin-inputs");s==null||s.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(l=>!l.value)??t[t.length-1];a==null||a.focus()}}),(n=t[0])==null||n.focus()}class oi{constructor(e="light",r,t=Ve,s){this.theme=e,this.overrides=r,this.tokens=gt(e,r),this.displayDecimals=t,this.pinKeyboard=s,hs()}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=gt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((s,n)=>{var E;V();const o=[...e],a=Ws(o,this.tokens,t,this.messages),l=ne();q(a);let p=!1;const h=()=>{p||(p=!0,a.remove(),l())};let _=null;const g=A=>{h(),s(A)},w=()=>{h(),_?n(_):s(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(A=>{A.addEventListener("click",()=>{const T=A.dataset.walletAddress??"",R=parseInt(A.dataset.walletIndex??"0",10),D=o.find(F=>F.index===R);g({address:T,index:R,name:D==null?void 0:D.name})})})})();const x=a.querySelector("#__crossx-add-wallet-error"),y=a.querySelector("#__crossx-add-wallet-btn");y&&y.addEventListener("click",async()=>{y.disabled=!0,x&&(x.hidden=!0,x.textContent="");try{const A=await r();o.push(A);const T=a.querySelector("#__crossx-wallet-list");if(T){const R=document.createElement("button");R.className="__crossx-wallet-item",R.dataset.walletIndex=String(A.index),R.dataset.walletAddress=A.address,R.innerHTML=`${Mt(A.address,A.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${m(Lt(A))}</span><span class="__crossx-wallet-addr">${It(A.address)}</span></span>`,R.addEventListener("click",()=>g(A)),T.appendChild(R);try{R.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}y.disabled=!1}catch(A){const T=A instanceof u&&A.code===d.ADDRESS_LIMIT_EXCEEDED,R=this.resolveAddWalletErrorMessage(A);x&&(x.textContent=R,x.hidden=!1),T?(y.disabled=!0,y.setAttribute("aria-disabled","true")):y.disabled=!1,_=A}}),(E=a.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",w),a.addEventListener("click",A=>{A.target===a&&w()});const b=A=>{A.key==="Escape"&&(document.removeEventListener("keydown",b),w())};document.addEventListener("keydown",b)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,l;V();const r=Hs(this.tokens,this.messages),t=ne();q(r);let s=!1,n=null;const o=()=>{s||(s=!0,n&&document.removeEventListener("keydown",n),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",o),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),r.addEventListener("click",p=>{p.target===r&&o()}),n=p=>{p.key==="Escape"&&o()},document.addEventListener("keydown",n)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof u&&e.code===d.ADDRESS_LIMIT_EXCEEDED){const s=e.details,n=typeof(s==null?void 0:s.limit)=="number"?s.limit:Ee;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(n))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(s=>Object.values(pe).includes(s)&&String(s).trim()!==""))??[];return new Promise(s=>{var g,w,f,x;V();const n=zs(this.tokens,r,this.messages),o=ne();q(n);const a=()=>{n.remove(),o()},l=y=>{a(),s({type:"oauth",provider:y})},p=y=>{a(),s({type:"external",walletId:y})},h=()=>{a(),s(null)};(g=n.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>l("apple")),(w=n.querySelector("#__crossx-google-btn"))==null||w.addEventListener("click",()=>l("google")),(f=n.querySelector("#__crossx-connect-other-wallet-btn"))==null||f.addEventListener("click",y=>{const E=y.currentTarget.dataset.walletId??"";E&&p(E)}),(x=n.querySelector("#__crossx-close-btn"))==null||x.addEventListener("click",h),n.addEventListener("click",y=>{y.target===n&&h()}),n.querySelectorAll(".__crossx-login-terms-link").forEach(y=>{y.addEventListener("click",b=>b.stopPropagation())});const _=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",_),h())};document.addEventListener("keydown",_)})}showSessionAlert(e){return new Promise(r=>{var h,_,g;V();const t=this.messages,s=js(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"}),n=ne();q(s);let o=!1;const a=()=>{o||(o=!0,s.remove(),n())},l=()=>{a(),r("signout")},p=()=>{a(),r("signin-again")};(h=s.querySelector("#__crossx-session-signout"))==null||h.addEventListener("click",l),(_=s.querySelector("#__crossx-session-signin"))==null||_.addEventListener("click",p),(g=s.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",l)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,l,p;V();const s=Ys(this.tokens,r);q(s);const n=()=>s.remove(),o=()=>{n(),t("recover")};if((a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const h=()=>{n(),t("skip")};(l=s.querySelector("#__crossx-skip-btn"))==null||l.addEventListener("click",h),(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",h),s.addEventListener("click",g=>{g.target===s&&h()});const _=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",_),h())};document.addEventListener("keydown",_)}})}showPinSetupPrompt(e){return new Promise(r=>{V();const t=this.messages,s={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pin_notice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},n={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=wt(this.tokens,Qs(s)),l=ne();q(a);let p=!1;const h=()=>{p||(p=!0,a.remove(),l())},_=E=>{h(),r(E)},g=()=>{h(),r(null)},w=a.querySelector(".__crossx-card"),f={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},x=E=>{var A;w.innerHTML=Be({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(w),(A=w.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),Ue(w,T=>{T===E?_(E):y(n.mismatchError)},g)},y=E=>{var A;w.innerHTML=Be({title:n.title,headerSubtitle:n.headerSubtitle,subtitle:n.subtitle,errorMessage:E}),this.applyPinKeyboardMode(w),(A=w.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),Ue(w,T=>{const R=ei(T,f);R?y(R):x(T)},g)};(()=>{var K;const E=Array.from(w.querySelectorAll(".__crossx-pw-notice-item")),A=w.querySelector("#__crossx-pin-notice-next"),T=new Set;A.removeAttribute("disabled");const R=A.dataset.nextLabel??"Next",D=A.dataset.submitLabel??"I Understand",F=()=>{const I=T.size===E.length;A.classList.toggle("--disabled",!I),A.textContent=D||R},C=(I,L)=>{if(T.has(L))return;const $=I.querySelector(`#__crossx-notice-check-${L}`);T.add(L),$.classList.add("--checked"),I.setAttribute("aria-checked","true"),F()},O=(I,L)=>{if(!T.has(L))return;const $=I.querySelector(`#__crossx-notice-check-${L}`);T.delete(L),$.classList.remove("--checked"),I.setAttribute("aria-checked","false"),F()};E.forEach(I=>{const L=parseInt(I.dataset.checkIndex??"0",10);I.addEventListener("click",()=>{T.has(L)?O(I,L):C(I,L)}),I.addEventListener("keydown",$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),T.has(L)?O(I,L):C(I,L))})}),A.addEventListener("click",()=>{if(T.size===E.length){y(e==null?void 0:e.errorMessage);return}const I=E.find($=>{const X=parseInt($.dataset.checkIndex??"0",10);return!T.has(X)});if(!I)return;const L=parseInt(I.dataset.checkIndex??"0",10);I.scrollIntoView({behavior:"smooth",block:"nearest"}),I.classList.add("--highlight"),setTimeout(()=>{I.classList.remove("--highlight"),C(I,L)},400)}),(K=w.querySelector("#__crossx-close-btn"))==null||K.addEventListener("click",g)})(),a.addEventListener("click",E=>{E.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var b;V();const s=this.messages,n=(e==null?void 0:e.verifyMode)===!0,o=n?(s==null?void 0:s.verify_pin_title)??"Verify Your PIN":(s==null?void 0:s.pin_input_title)??"Enter PIN",a=n?(s==null?void 0:s.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(s==null?void 0:s.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",l=(s==null?void 0:s.pin_locked_failure_warning)??"Your account will be locked after further failures.",p=wt(this.tokens,Be({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:l,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),h=ne();q(p);let _=!1;const g=()=>{_||(_=!0,p.remove(),h())},w=E=>{g(),r(E)},f=()=>{g(),r(null)},x=E=>{g(),t(E)},y=p.querySelector(".__crossx-card");this.applyPinKeyboardMode(y),(b=y.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",f),Ue(y,w,f,x,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,l),p.addEventListener("click",E=>{E.target===p&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var l;V();const t=Xs(this.tokens,e);q(t);const s=()=>t.remove(),n=p=>{s(),r(p)},o=()=>{s(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),ni(t,n,o),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),t.addEventListener("click",p=>{p.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var p;V();const{overlay:s,startCountdown:n}=Zs(this.tokens,e,r);q(s);const o=()=>{l(),s.remove()},a=()=>{o(),t()},l=n(a);(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),s.addEventListener("click",h=>{h.target===s&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,l;V();const t=Ps(e,this.tokens,this.messages);q(t);const s=()=>t.remove(),n=()=>{s(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",n),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),t.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",h=>{var g;h.stopPropagation();const _=p.dataset.copy;_&&((g=navigator.clipboard)==null||g.writeText(_).catch(()=>{}))})}),t.addEventListener("click",p=>{p.target===t&&n()});const o=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",o),n())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{V();const s=Cs(e,this.tokens,this.messages);q(s);const n=()=>s.remove();let o=!1;const a=()=>{o||(o=!0,n(),t())},l=()=>{var h,_;(h=s.querySelector("#__crossx-done-btn"))==null||h.addEventListener("click",a),(_=s.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",a),s.addEventListener("click",g=>{g.target===s&&a()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),a())};document.addEventListener("keydown",p)};r.then(p=>{o||(Os(s,p,this.tokens,this.messages),l())})})}requestConfirmation(e){return new Promise(r=>{var p,h,_;V();let t;e.type==="sign-message"?t=Ds(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Ls(e,this.tokens,this.messages):e.type==="sign"?t=Ss(e,this.tokens,this.displayDecimals,this.messages):t=As(e,this.tokens,this.displayDecimals,this.messages);const s=ne();q(t);const n=()=>{t.remove(),s()},o=()=>{n(),r(!0)},a=()=>{n(),r(!1)};(p=t.querySelector("#__crossx-confirm-btn"))==null||p.addEventListener("click",o),(h=t.querySelector("#__crossx-cancel-btn"))==null||h.addEventListener("click",a),(_=t.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",w=>{var x;w.stopPropagation();const f=g.dataset.copy;f&&((x=navigator.clipboard)==null||x.writeText(f).catch(()=>{}))})}),ds(t),t.addEventListener("click",g=>{g.target===t&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)})}}class ai{constructor(e,r,t,s=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=s}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:s,chainId:n}=this.mapToNativeParams(e),o={operation:t,payload:s,dappOrigin:this.getOrigin(),chainId:n};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 u(d.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t){const s=this.getBridge();if(this.shouldDelegateToBridge()&&(s!=null&&s.showWalletSelector))try{const n=await s.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===n.address.toLowerCase());return{address:n.address,index:(o==null?void 0:o.index)??n.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 $t{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 ci(i,e){if(!i.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3061
+ </svg>`;function pi(i,e,r){var n;const t=i.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const l=o.value.replace(/\D/g,"");o.value=l?l[0]:"",l&&a<3&&t[a+1].focus();const p=Array.from(t).map(h=>h.value).join("");p.length===4&&setTimeout(()=>e(p),200)}),o.addEventListener("keydown",l=>{l.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),l.key==="Escape"&&r()}),o.addEventListener("keypress",l=>{/[0-9]/.test(l.key)||l.preventDefault()}),o.addEventListener("paste",l=>{var _;l.preventDefault();const p=(((_=l.clipboardData)==null?void 0:_.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!p)return;p.split("").forEach((g,m)=>{t[m]&&(t[m].value=g)});const h=Math.min(p.length,3);t[h].focus(),p.length===4&&setTimeout(()=>e(p),200)})});const s=i.querySelector(".__crossx-pin-inputs");s==null||s.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(l=>!l.value)??t[t.length-1];a==null||a.focus()}}),(n=t[0])==null||n.focus()}class hi{constructor(e="light",r,t=Ke,s){this.theme=e,this.overrides=r,this.tokens=ft(e,r),this.displayDecimals=t,this.pinKeyboard=s,ws()}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=ft(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((s,n)=>{var E;V();const o=[...e],a=zs(o,this.tokens,t,this.messages),l=ne();q(a);let p=!1;const h=()=>{p||(p=!0,a.remove(),l())};let _=null;const g=A=>{h(),s(A)},m=()=>{h(),_?n(_):s(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(A=>{A.addEventListener("click",()=>{const k=A.dataset.walletAddress??"",R=parseInt(A.dataset.walletIndex??"0",10),D=o.find(M=>M.index===R);g({address:k,index:R,name:D==null?void 0:D.name})})})})();const x=a.querySelector("#__crossx-add-wallet-error"),y=a.querySelector("#__crossx-add-wallet-btn");y&&y.addEventListener("click",async()=>{y.disabled=!0,x&&(x.hidden=!0,x.textContent="");try{const A=await r();o.push(A);const k=a.querySelector("#__crossx-wallet-list");if(k){const R=document.createElement("button");R.className="__crossx-wallet-item",R.dataset.walletIndex=String(A.index),R.dataset.walletAddress=A.address,R.innerHTML=`${Mt(A.address,A.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${f(Ft(A))}</span><span class="__crossx-wallet-addr">${f(Tt(A.address))}</span></span>`,R.addEventListener("click",()=>g(A)),k.appendChild(R);try{R.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}y.disabled=!1}catch(A){const k=A instanceof u&&A.code===d.ADDRESS_LIMIT_EXCEEDED,R=this.resolveAddWalletErrorMessage(A);x&&(x.textContent=R,x.hidden=!1),k?(y.disabled=!0,y.setAttribute("aria-disabled","true")):y.disabled=!1,_=A}}),(E=a.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",m),a.addEventListener("click",A=>{A.target===a&&m()});const b=A=>{A.key==="Escape"&&(document.removeEventListener("keydown",b),m())};document.addEventListener("keydown",b)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,l;V();const r=js(this.tokens,this.messages),t=ne();q(r);let s=!1,n=null;const o=()=>{s||(s=!0,n&&document.removeEventListener("keydown",n),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",o),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),r.addEventListener("click",p=>{p.target===r&&o()}),n=p=>{p.key==="Escape"&&o()},document.addEventListener("keydown",n)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof u&&e.code===d.ADDRESS_LIMIT_EXCEEDED){const s=e.details,n=typeof(s==null?void 0:s.limit)=="number"?s.limit:Te;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(n))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(s=>Object.values(he).includes(s)&&String(s).trim()!==""))??[];return new Promise(s=>{var g,m,w,x;V();const n=Qs(this.tokens,r,this.messages),o=ne();q(n);const a=()=>{n.remove(),o()},l=y=>{a(),s({type:"oauth",provider:y})},p=y=>{a(),s({type:"external",walletId:y})},h=()=>{a(),s(null)};(g=n.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>l("apple")),(m=n.querySelector("#__crossx-google-btn"))==null||m.addEventListener("click",()=>l("google")),(w=n.querySelector("#__crossx-connect-other-wallet-btn"))==null||w.addEventListener("click",y=>{const E=y.currentTarget.dataset.walletId??"";E&&p(E)}),(x=n.querySelector("#__crossx-close-btn"))==null||x.addEventListener("click",h),n.addEventListener("click",y=>{y.target===n&&h()}),n.querySelectorAll(".__crossx-login-terms-link").forEach(y=>{y.addEventListener("click",b=>b.stopPropagation())});const _=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",_),h())};document.addEventListener("keydown",_)})}showSessionAlert(e){return new Promise(r=>{var h,_,g;V();const t=this.messages,s=ei(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"}),n=ne();q(s);let o=!1;const a=()=>{o||(o=!0,s.remove(),n())},l=()=>{a(),r("signout")},p=()=>{a(),r("signin-again")};(h=s.querySelector("#__crossx-session-signout"))==null||h.addEventListener("click",l),(_=s.querySelector("#__crossx-session-signin"))==null||_.addEventListener("click",p),(g=s.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",l)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,l,p;V();const s=ti(this.tokens,r);q(s);const n=()=>s.remove(),o=()=>{n(),t("recover")};if((a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const h=()=>{n(),t("skip")};(l=s.querySelector("#__crossx-skip-btn"))==null||l.addEventListener("click",h),(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",h),s.addEventListener("click",g=>{g.target===s&&h()});const _=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",_),h())};document.addEventListener("keydown",_)}})}showPinSetupPrompt(e){return new Promise(r=>{V();const t=this.messages,s={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pin_notice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},n={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=mt(this.tokens,ni(s)),l=ne();q(a);let p=!1;const h=()=>{p||(p=!0,a.remove(),l())},_=E=>{h(),r(E)},g=()=>{h(),r(null)},m=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."},x=E=>{var A;m.innerHTML=$e({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(m),(A=m.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),Be(m,k=>{k===E?_(E):y(n.mismatchError)},g)},y=E=>{var A;m.innerHTML=$e({title:n.title,headerSubtitle:n.headerSubtitle,subtitle:n.subtitle,errorMessage:E}),this.applyPinKeyboardMode(m),(A=m.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),Be(m,k=>{const R=oi(k,w);R?y(R):x(k)},g)};(()=>{var K;const E=Array.from(m.querySelectorAll(".__crossx-pw-notice-item")),A=m.querySelector("#__crossx-pin-notice-next"),k=new Set;A.removeAttribute("disabled");const R=A.dataset.nextLabel??"Next",D=A.dataset.submitLabel??"I Understand",M=()=>{const I=k.size===E.length;A.classList.toggle("--disabled",!I),A.textContent=D||R},P=(I,L)=>{if(k.has(L))return;const $=I.querySelector(`#__crossx-notice-check-${L}`);k.add(L),$.classList.add("--checked"),I.setAttribute("aria-checked","true"),M()},O=(I,L)=>{if(!k.has(L))return;const $=I.querySelector(`#__crossx-notice-check-${L}`);k.delete(L),$.classList.remove("--checked"),I.setAttribute("aria-checked","false"),M()};E.forEach(I=>{const L=parseInt(I.dataset.checkIndex??"0",10);I.addEventListener("click",()=>{k.has(L)?O(I,L):P(I,L)}),I.addEventListener("keydown",$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),k.has(L)?O(I,L):P(I,L))})}),A.addEventListener("click",()=>{if(k.size===E.length){y(e==null?void 0:e.errorMessage);return}const I=E.find($=>{const X=parseInt($.dataset.checkIndex??"0",10);return!k.has(X)});if(!I)return;const L=parseInt(I.dataset.checkIndex??"0",10);I.scrollIntoView({behavior:"smooth",block:"nearest"}),I.classList.add("--highlight"),setTimeout(()=>{I.classList.remove("--highlight"),P(I,L)},400)}),(K=m.querySelector("#__crossx-close-btn"))==null||K.addEventListener("click",g)})(),a.addEventListener("click",E=>{E.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var b;V();const s=this.messages,n=(e==null?void 0:e.verifyMode)===!0,o=n?(s==null?void 0:s.verify_pin_title)??"Verify Your PIN":(s==null?void 0:s.pin_input_title)??"Enter PIN",a=n?(s==null?void 0:s.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(s==null?void 0:s.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",l=(s==null?void 0:s.pin_locked_failure_warning)??"Your account will be locked after further failures.",p=mt(this.tokens,$e({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:l,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),h=ne();q(p);let _=!1;const g=()=>{_||(_=!0,p.remove(),h())},m=E=>{g(),r(E)},w=()=>{g(),r(null)},x=E=>{g(),t(E)},y=p.querySelector(".__crossx-card");this.applyPinKeyboardMode(y),(b=y.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",w),Be(y,m,w,x,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,l),p.addEventListener("click",E=>{E.target===p&&w()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var l;V();const t=ri(this.tokens,e);q(t);const s=()=>t.remove(),n=p=>{s(),r(p)},o=()=>{s(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),pi(t,n,o),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),t.addEventListener("click",p=>{p.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var p;V();const{overlay:s,startCountdown:n}=ii(this.tokens,e,r);q(s);const o=()=>{l(),s.remove()},a=()=>{o(),t()},l=n(a);(p=s.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),s.addEventListener("click",h=>{h.target===s&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,l;V();const t=Ms(e,this.tokens,this.messages);q(t);const s=()=>t.remove(),n=()=>{s(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",n),(l=t.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),t.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",h=>{var g;h.stopPropagation();const _=p.dataset.copy;_&&((g=navigator.clipboard)==null||g.writeText(_).catch(()=>{}))})}),t.addEventListener("click",p=>{p.target===t&&n()});const o=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",o),n())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{V();const s=$s(e,this.tokens,this.messages);q(s);const n=()=>s.remove();let o=!1;const a=()=>{o||(o=!0,n(),t())},l=()=>{var h,_;(h=s.querySelector("#__crossx-done-btn"))==null||h.addEventListener("click",a),(_=s.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",a),s.addEventListener("click",g=>{g.target===s&&a()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),a())};document.addEventListener("keydown",p)};r.then(p=>{o||(Bs(s,p,this.tokens,this.messages),l())})})}requestConfirmation(e){return new Promise(r=>{var p,h,_;V();let t;e.type==="sign-message"?t=Us(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Ws(e,this.tokens,this.messages):e.type==="sign"?t=ks(e,this.tokens,this.displayDecimals,this.messages):t=Cs(e,this.tokens,this.displayDecimals,this.messages);const s=ne();q(t);const n=()=>{t.remove(),s()},o=()=>{n(),r(!0)},a=()=>{n(),r(!1)};(p=t.querySelector("#__crossx-confirm-btn"))==null||p.addEventListener("click",o),(h=t.querySelector("#__crossx-cancel-btn"))==null||h.addEventListener("click",a),(_=t.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",m=>{var x;m.stopPropagation();const w=g.dataset.copy;w&&((x=navigator.clipboard)==null||x.writeText(w).catch(()=>{}))})}),gs(t),t.addEventListener("click",g=>{g.target===t&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)})}}class ui{constructor(e,r,t,s=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=s}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:s,chainId:n}=this.mapToNativeParams(e),o={operation:t,payload:s,dappOrigin:this.getOrigin(),chainId:n};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 u(d.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t){const s=this.getBridge();if(this.shouldDelegateToBridge()&&(s!=null&&s.showWalletSelector))try{const n=await s.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===n.address.toLowerCase());return{address:n.address,index:(o==null?void 0:o.index)??n.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 Bt{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 Ut(i,e){if(!i.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3062
3062
  Set the projectId field in SDKConfig when calling createCROSSxSDK().
3063
- Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);i.debug;const r=he.production,t={...i,oauthServiceUrl:r.oauthServiceUrl,legacyOauthServiceUrl:r.legacyOauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},s={gatewayUrl:r.walletGatewayUrl,projectId:i.projectId},n=t.authMode!=="cookie"&&pt.isAvailable();!n&&t.authMode!=="cookie"&&c.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=n;const o=n?new pt(i.projectId):new Tr,a=new Cr,l=new Vr,p=new oe,h=new $t,_=new qe,g=new Lr(s,l);let w;i.useMockWallet?(c.log("[CROSSx] Mock Wallet Provider 사용"),w=new ss(o,_)):(c.log("[CROSSx] Remote Wallet Provider 사용"),w=new ae(s,o,l,h,_,g));let f=null;const x=()=>{var C;return((C=f==null?void 0:f.isAuthenticatedViaRNBridge)==null?void 0:C.call(f))??!1},y=()=>{var C;return(C=f==null?void 0:f.assertRNBridgeSessionActive)==null?void 0:C.call(f)},b=C=>{var O;(O=f==null?void 0:f.clearRNBridgeDelegation)==null||O.call(f,C)};w=new ns(w,()=>{var C;return(C=f==null?void 0:f.getRNBridge)==null?void 0:C.call(f)},x,y,()=>i.appName,b);const E=new we(s,l),A=new oi(i.theme??"light",i.themeTokens,i.displayDecimals,i.pinKeyboard),T=new ai(A,()=>{var C;return(C=f==null?void 0:f.getRNBridge)==null?void 0:C.call(f)},()=>typeof window<"u"?window.location.origin:"http://localhost",x),R=e!=null&&e.wrapConfirmation?e.wrapConfirmation(T):T,D=new Ae(t,s,o,a,l,p,w,h,R,E,_,g);f=D;const F=D.signInUseCase;return F&&typeof F.setFreshTokenCallback=="function"&&F.setFreshTokenCallback(()=>D.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=D),D}function li(i){const e=di(i),r=pi(e),t=JSON.parse(r);ui(t);const{data:s}=t;return{status:t.status,state:t.state,firebaseToken:s.accessToken,provider:s.provider,email:s.email,providerSub:s.sub,tokenType:s.tokenType,expiresIn:s.expiresIn,raw:t}}function di(i){if(i.includes("://")&&i.includes("?")){const e=new URL(i),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return i}function pi(i){if(i.startsWith("{"))return i;if(i.startsWith("%7B")||i.startsWith("%7b"))return decodeURIComponent(i);const e=hi(i);return decodeURIComponent(e)}function hi(i){if(typeof atob=="function")return atob(i);if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function ui(i){if(typeof i!="object"||i===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=i;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}exports.CONNECT_OTHER_WALLET_DISPLAY_ORDER=mt;exports.CROSSxError=u;exports.CROSSxEthereumProvider=St;exports.CROSSxSDK=Ae;exports.ChainId=Zt;exports.ConnectOtherWalletItem=pe;exports.ErrorCode=d;exports.MNEMONIC_ADDRESS_LIMIT=Ee;exports.PinMemoryStore=qe;exports.TokenMemoryStore=$t;exports.WALLET_BRAND_NAME=Te;exports.createCROSSxSDK=ci;exports.getConnectOtherWalletLabel=yt;exports.getWalletBrowserInfo=me;exports.isWalletInAppBrowser=Jr;exports.parseOAuthDeeplink=li;exports.waitForWalletBrowser=Zr;
3063
+ Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);i.debug;const r=ue.production,t={...i,oauthServiceUrl:r.oauthServiceUrl,legacyOauthServiceUrl:r.legacyOauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},s={gatewayUrl:r.walletGatewayUrl,projectId:i.projectId},n=t.authMode!=="cookie"&&ut.isAvailable();!n&&t.authMode!=="cookie"&&c.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=n;const o=n?new ut(i.projectId):new Fr,a=new Br,l=new Jr,p=new oe,h=new Bt,_=new qe,g=new Hr(s,l);let m;i.useMockWallet?(c.log("[CROSSx] Mock Wallet Provider 사용"),m=new ls(o,_)):(c.log("[CROSSx] Remote Wallet Provider 사용"),m=new ae(s,o,l,h,_,g));let w=null;const x=()=>{var P;return((P=w==null?void 0:w.isAuthenticatedViaRNBridge)==null?void 0:P.call(w))??!1},y=()=>{var P;return(P=w==null?void 0:w.assertRNBridgeSessionActive)==null?void 0:P.call(w)},b=P=>{var O;(O=w==null?void 0:w.clearRNBridgeDelegation)==null||O.call(w,P)};m=new ps(m,()=>{var P;return(P=w==null?void 0:w.getRNBridge)==null?void 0:P.call(w)},x,y,()=>i.appName,b);const E=new me(s,l),A=new hi(i.theme??"light",i.themeTokens,i.displayDecimals,i.pinKeyboard),k=new ui(A,()=>{var P;return(P=w==null?void 0:w.getRNBridge)==null?void 0:P.call(w)},()=>typeof window<"u"?window.location.origin:"http://localhost",x),R=e!=null&&e.wrapConfirmation?e.wrapConfirmation(k):k,D=new ye(t,s,o,a,l,p,m,h,R,E,_,g);w=D;const M=D.signInUseCase;return M&&typeof M.setFreshTokenCallback=="function"&&M.setFreshTokenCallback(()=>D.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=D),D}const _i=Ut;function xi(i){const e=gi(i),r=fi(e),t=JSON.parse(r);mi(t);const{data:s}=t;return{status:t.status,state:t.state,firebaseToken:s.accessToken,provider:s.provider,email:s.email,providerSub:s.sub,tokenType:s.tokenType,expiresIn:s.expiresIn,raw:t}}function gi(i){if(i.includes("://")&&i.includes("?")){const e=new URL(i),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return i}function fi(i){if(i.startsWith("{"))return i;if(i.startsWith("%7B")||i.startsWith("%7b"))return decodeURIComponent(i);const e=wi(i);return decodeURIComponent(e)}function wi(i){if(typeof atob=="function")return atob(i);if(typeof Buffer<"u")return Buffer.from(i,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function mi(i){if(typeof i!="object"||i===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=i;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}exports.CONNECT_OTHER_WALLET_DISPLAY_ORDER=yt;exports.CROSSxError=u;exports.CROSSxEthereumProvider=Ve;exports.CROSSxSDK=ye;exports.ChainId=rr;exports.ConnectOtherWalletItem=he;exports.ErrorCode=d;exports.MNEMONIC_ADDRESS_LIMIT=Te;exports.ONEpocketError=u;exports.ONEpocketEthereumProvider=Ve;exports.ONEpocketSDK=ye;exports.PinMemoryStore=qe;exports.TokenMemoryStore=Bt;exports.WALLET_BRAND_NAME=Ne;exports.createCROSSxSDK=Ut;exports.createONEpocketSDK=_i;exports.getConnectOtherWalletLabel=bt;exports.getWalletBrowserInfo=be;exports.isWalletInAppBrowser=ss;exports.parseOAuthDeeplink=xi;exports.waitForWalletBrowser=is;