@nexus-cross/crossx-sdk-core 2.3.10-beta.6 → 2.3.10-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,13 @@
1
- var CROSSx=function(j){"use strict";var mc=Object.defineProperty;var yc=(j,p,g)=>p in j?mc(j,p,{enumerable:!0,configurable:!0,writable:!0,value:g}):j[p]=g;var O=(j,p,g)=>yc(j,typeof p!="symbol"?p+"":p,g);var Rt,hn;var p=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(p||{});class g extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,g.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const fn=2e3,wr=6e4,_n=1e3,gn=1e4,xn="0x77359400",mr="0x3B9ACA00",yr=130,kt=6,br=18,Sr=3e4,wn=5*60*1e3,mn=30*1e3,ot=100,yn="crossx-sdk-js/2.3.10-beta.6",at="ONEwallet";var Ue=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(Ue||{});const bn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:at},vr=["crossx","io.metamask","com.binance.wallet"];function Er(s){return bn[s]??s}function Sn(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...vr]:[]}const ct={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},vn=Object.fromEntries(Object.entries(ct).map(([s,e])=>[s,e.caipId])),En=new Map(Object.values(ct).map(s=>[s.caipId,s]));new Map(Object.values(ct).map(s=>[s.chainId,s]));const An={symbol:"",decimals:18};function Ct(s){var e;return((e=En.get(s))==null?void 0:e.nativeCurrency)??An}class Ar{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 g(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new g(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let ye=null;function bc(s){}function Ir(s){ye=s}const d={info(...s){if(ye){ye.log(...s);return}console.log(...s)},log(...s){if(ye){ye.log(...s);return}},warn(...s){if(ye){ye.warn(...s);return}},error(...s){if(ye){ye.error(...s);return}}},In={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
+ var CROSSx=function(j){"use strict";var vc=Object.defineProperty;var Ec=(j,p,g)=>p in j?vc(j,p,{enumerable:!0,configurable:!0,writable:!0,value:g}):j[p]=g;var P=(j,p,g)=>Ec(j,typeof p!="symbol"?p+"":p,g);var Rt,pn;var p=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(p||{});class g extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,g.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const _n=2e3,mr=6e4,gn=1e3,xn=1e4,wn="0x77359400",yr="0x3B9ACA00",br=130,kt=6,Sr=18,vr=3e4,mn=5*60*1e3,yn=30*1e3,ot=100,bn="crossx-sdk-js/2.3.10-beta.7",at="ONEwallet";var Ue=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(Ue||{});const Sn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:at},Er=["crossx","io.metamask","com.binance.wallet"];function Ar(s){return Sn[s]??s}function vn(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...Er]:[]}const ct={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},En=Object.fromEntries(Object.entries(ct).map(([s,e])=>[s,e.caipId])),An=new Map(Object.values(ct).map(s=>[s.caipId,s]));new Map(Object.values(ct).map(s=>[s.chainId,s]));const In={symbol:"",decimals:18};function Ct(s){var e;return((e=An.get(s))==null?void 0:e.nativeCurrency)??In}class Ir{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 g(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new g(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let ye=null;function Ac(s){}function Tr(s){ye=s}const d={info(...s){if(ye){ye.log(...s);return}console.log(...s)},log(...s){if(ye){ye.log(...s);return}},warn(...s){if(ye){ye.warn(...s);return}},error(...s){if(ye){ye.error(...s);return}}},Tn={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:"다시 로그인"},Tr={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:at,login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
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:"다시 로그인"},Rr={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:at,login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
5
5
 
6
- For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},Tn={ko:In,en:Tr};function be(s="en",e){return Tn[s]??Tr}function Rn(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Rr="crossx_access_token",kr="crossx_refresh_token",Cr="crossx_user_info",Tt=class Tt{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${u}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new g(p.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=Rn(this.getLocale()),c=`${o}${i}`,l=c.includes("?")?"&":"?",u=`${c}${l}locale=${a}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const h=await this.oauth.openAuth({authUrl:u,expectedOrigin:new URL(o).origin});r=h.token,t=h.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new g(p.OAUTH_POPUP_BLOCKED,i):new g(p.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const h=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=h.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new g(p.AUTH_FAILED,"Access token 검증 실패");const h=u.payload;r={id:h.sub,email:h.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new g(p.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:h,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let f,x,w;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),x=(i=A.firebase)==null?void 0:i.sign_in_provider;const R=((o=A.firebase)==null?void 0:o.identities)??{};w=A.email??((a=R.email)==null?void 0:a[0]),x==="google.com"?f=(c=R["google.com"])==null?void 0:c[0]:x==="apple.com"&&(f=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!f,"email:",w??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(h){const A=this.crypto.decodeJWT(h);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const R=await this.crypto.verifyJWT(h);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const k=R.payload,L=k.email??w??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",k.email??"(없음)","/ Firebase JWT:",w??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:k.sub,email:L,signInProvider:x,providerSub:f},this.tokenStore.set(h),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,h),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??r,signInProvider:x,providerSub:f},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const b=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,b),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new g(p.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new g(p.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof g&&e.code===p.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=Tt.REFRESH_RELOGIN_CODES.has(c.code);throw new g(u?p.SESSION_EXPIRED:p.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new g(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof g&&t.code===p.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof g&&e.code===p.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Cr);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(Rr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(kr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Cr),await this.storage.remove(Rr),await this.storage.remove(kr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof g&&i.code===p.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(i.code===p.PROJECT_NOT_REGISTERED||i.code===p.PROJECT_ID_MISSING||i.code===p.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};Tt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Nt=Tt;class kn{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Cn{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new g(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Pt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Nn{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new g(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Pn{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function On(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class fe{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await fe.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=fe.getBridge(),!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new g(p.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=On(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new g(p.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0,a=n.provider==="google"||n.provider==="apple"?n.provider:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:o,walletProvider:a}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new g(p.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new g(p.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 g(p.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof g)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new g(p.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new g(p.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new g(p.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof g?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new g(p.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new g(p.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 g(p.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof g?r:(d.warn("[RNBridge] Session restore Firebase token request failed",r),new g(p.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 g(p.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var lt={environment:"production"};const He={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",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",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",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 Ln(s){const e=s.environment,r=e&&e in He?He[e]:null;if(!r)return null;const t=s.overrides;if(!t)return r;const n={...r};for(const[i,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(n[i]=o);return n}function Ot(){try{if(typeof lt<"u"){const s=typeof lt=="string"?JSON.parse(lt):lt,e=Ln(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in He)return He[s]}catch{}return He.production}function Nr(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Dn(s,e=kt){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(br),n=r/t,o=(r%t).toString().padStart(br,"0"),a=Nr(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function dt(s,e,r,t=kt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=Nr(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Bn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==yr)throw new g(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${yr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Mn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function $n(s,e){const r=Fn(e);if(s==="0"){if(r!==void 0&&r!==0)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Fn(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Ge{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new g(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){var c,l;if((l=(c=this.deps).isRNBridgeMode)!=null&&l.call(c))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((u,h)=>{i=u,o=h});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const h=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!h)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(h),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const u=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async h=>{this.deps.pinStore.set(h);try{return await this.deps.walletProvider.verifyPin(h)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(_){if(this.deps.pinStore.clear(),_ instanceof g){if(_.code===p.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(_.code===p.PIN_INVALID)return{ok:!1,error:_.message};if(_.code===p.PIN_LOCKED)return Ge.buildPinLockedResult(_,a)}throw _}}});if(!u)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(u),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(u){if(u instanceof g&&(u.code===p.AUTH_NOT_AUTHENTICATED||u.code===p.AUTH_TOKEN_EXPIRED||u.code===p.SESSION_EXPIRED)&&u.code!==p.SESSION_EXPIRED){const h=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:h.session_alert_title,message:h.alert_session_expired,email:_?this.deps.maskEmail(_,h.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(u),u}throw o(u),u}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Ge.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof g&&(t=Ge.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===p.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===p.PIN_INVALID)return{errorMessage:e.message};if(e.code===p.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Ge.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Wn{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new g(p.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function Un(s){return s==="google"||s==="apple"}class Hn{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Un(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof g&&r.code===p.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof g&&r.code===p.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof g)||r.code!==p.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new g(p.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new g(p.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Gn{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const h=o.find(_=>_.address.toLowerCase()===r.toLowerCase());h?c=h:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(h=>h.index===e)??o[0]:c=o[0];l?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const u=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,u?{walletName:t}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Kn{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const h=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!h){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(h.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const _=h.pinStatus;if(o=_.maxAttempts,i=o-_.remainingAttempts,_.remainingAttempts===0&&_.lockExpiresAt){const f=_.lockExpiresAt*1e3,x=Math.max(1,Math.round((f-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${w}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(h){if(!(h instanceof g))throw h;if(h.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const _=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:f?this.deps.maskEmail(f,_.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),h}if(h.code===p.MIGRATION_PIN_LOCKED){const _=h.details;if(o=(_==null?void 0:_.maxAttempts)??5,(_==null?void 0:_.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const f=((_==null?void 0:_.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((f-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",h),h}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof g&&u.code===p.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof g&&u.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const h=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:h.session_alert_title,message:h.alert_session_expired,email:_?this.deps.maskEmail(_,h.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const w=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",w.address),w}catch(w){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",w),w}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class qn{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,h,_]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=h,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const f=_;if(f){const x=mr;c.maxFeePerGas=`0x${(BigInt(f)+BigInt(x)).toString(16)}`,c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=xn,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=mr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Vn{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function zn(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class Jn{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e,r){var n,i,o,a,c;const t={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:zn((a=e.user)==null?void 0:a.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(t),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...r?{source:r}:{}})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class jn{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 g(p.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 Yn{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new g(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new g(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Xn{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",o);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(o);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new g(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof g&&r.code===p.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new g(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function Pr(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Zn{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new g(p.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new g(p.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new g(p.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new g(p.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=Pr(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof g?c:new g(p.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(Pr(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new g(p.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof g?i:new g(p.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof g&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:p.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:p.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:p.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:p.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new g(n.code,n.message)}}function Lt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Fe=class Fe extends Pn{constructor(e,r,t,n,i,o,a,c,l,u,h){var _,f;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._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&&Ir(e.logger),this.confirmation=l,this.pinStore=h??new Pt,this.stateManager=new Jn({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:w,walletName:b})=>{const A={address:x,index:w};b!==void 0&&(A.walletName=b),this.emit("addressChanged",A)},emitAuthChanged:({isAuthenticated:x,address:w,userId:b,source:A})=>{this.emit("authChanged",{isAuthenticated:x,address:w,userId:b,...A?{source:A}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Fe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ge({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Lt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new Wn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Gn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,w,b)=>this.setActiveWallet(x,w,b)}),this.migrationOrchestrator=new Kn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,w)=>this.migrateWalletUseCase.execute(x,w),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Lt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new qn({getActiveAddress:()=>this.address,estimateGas:(x,w)=>this.estimateGas(x,w),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,w,b)=>this.jsonRpc.call(x,w,b)}),this.signatureVerifier=new Vn(this.crypto),this.addressResolverService=new jn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Yn({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Xn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,w)=>this.setActiveWallet(x,w),showWalletCreated:()=>{var x,w;return((w=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:w.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Zn({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Hn({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:x=>{this._isRecoveringSession=x},setAuthenticated:x=>{this.authenticated=x},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:x=>this.signInUseCase.execute(x),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:x=>this.confirmation.showSessionAlert(x),clearAuthState:()=>this.clearAuthState(),applyAuthResult:x=>this.applyAuthResult(x),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Lt}),this.chainRegistry=u,this.jsonRpc=new Nn(u,i),this.signInUseCase=new Nt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new kn(this.internalConfig,t,c),this.migrateWalletUseCase=new Cn(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(f=a.setTokenRefresher)==null||f.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.3.10-beta.6 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=Ot();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Fe.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),u=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,u?{walletName:u}:void 0);else try{await this.loadWalletAfterAuth(o,a,u)}catch(h){if(h instanceof g&&h.code===p.PIN_CANCELLED)d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(h instanceof g&&(h.code===p.SESSION_EXPIRED||h.code===p.AUTH_NOT_AUTHENTICATED||h.code===p.USER_NOT_FOUND))d.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",h.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw h}}return this.initialized=!0,d.info("[CROSSx SDK] v2.3.10-beta.6 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new g(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!fe.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),d.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.10-beta.6",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new fe({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.10-beta.6",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof g&&r.code===p.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(d.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new g(p.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new g(p.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return fe.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&d.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let t=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:Sn(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new g(p.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(t);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof g?n:new g(p.AUTH_FAILED,"로그인에 실패했습니다",n)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof g&&i.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){var t,n;if(this.ensureInitialized(),this.authenticated)throw new g(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r,"external"),(n=(t=this.oauth).cancelPending)==null||n.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof g?i:new g(p.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c);return{...r,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:i}}catch(i){throw i instanceof g&&i.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),i}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new g(p.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 g?t:new g(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=fe.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new g(p.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 g&&t.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof g&&t.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof g?r:new g(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof g?e:new g(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof g?r:new g(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(be(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const n=fe.getBridge();if(n!=null&&n.signMessage){const o=await n.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:o.signature,message:r,address:this.address??""}}if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const i=await this.resolveAddress(t==null?void 0:t.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:i.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:i.address},execute:a=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,i.address)});return this.signatureVerifier.verifySignatureSigner(r,o.signature,i.address),{chainId:e,signature:o.signature,message:r,address:i.address}}catch(o){throw o instanceof g?o:new g(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}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 g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");$n(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Bn(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof g?i:new g(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(Fe.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return Mn(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(p.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 g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const h=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return h.txHash??h.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,yn).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??_n,i=gn,o=t.timeoutMs??wr,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var w,b;if(this._isAuthenticatedViaRNBridge){const A=fe.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??fn,l=i??((b=this._config.receiptPolling)==null?void 0:b.timeoutMs)??wr,u=Ct(e),h=r.from??"";let _,f;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{_=A;const R=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),k=r.value?BigInt(r.value):0n,L=dt(r.value,u.symbol,u.decimals,this._config.displayDecimals),U=dt("0x"+R.toString(16),u.symbol,u.decimals,this._config.displayDecimals),G=dt("0x"+(k+R).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:L,fees:U,total:G,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(f=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:h,to:r.to,amount:dt(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:r.to},x),f)throw f;return{chainId:e,txHash:a,receipt:_}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(p.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(p.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(p.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(p.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 g(p.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 g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(p.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Dn(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(p.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new Ar(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(p.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=fe.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){d.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,r){this.stateManager.applyAuthResult(e,r)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Ir(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Fe.WALLET_PREF_KEY="wallet_preference",Fe.OFFCHAIN_CHAIN_ID="0";let ut=Fe;class Qn{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Dt="crossx-sdk",ei=1,_e="data",Oe="keys",ht="aes-primary",ti=12;class Or{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,ei);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Oe)||i.createObjectStore(Oe)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Oe,ht);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(Oe,ht,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Dt)return null;try{const e=await this.openDB(Dt),r=e.transaction([Oe,_e],"readonly"),t=r.objectStore(Oe).get(ht),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(_e).getAll(),o=r.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Oe,ht,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Dt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(ti);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(_e,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Bt=crypto,Lr=s=>s instanceof CryptoKey,pt=new TextEncoder,Qe=new TextDecoder;function ri(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const si=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return si(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class se extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}se.code="ERR_JOSE_GENERIC";class he extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Mt extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Mt.code="ERR_JWT_EXPIRED";class Dr extends se{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Dr.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends se{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class ni extends se{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}ni.code="ERR_JWE_DECRYPTION_FAILED";class ii extends se{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ii.code="ERR_JWE_INVALID";class te extends se{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}te.code="ERR_JWS_INVALID";class xe extends se{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class oi extends se{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}oi.code="ERR_JWK_INVALID";class $t extends se{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}$t.code="ERR_JWKS_INVALID";class Ft extends se{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ft.code="ERR_JWKS_NO_MATCHING_KEY";class Br extends se{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Br.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Mr extends se{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}Mr.code="ERR_JWKS_TIMEOUT";class $r extends se{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}$r.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function et(s,e){return s.name===e}function Wt(s){return parseInt(s.name.slice(4),10)}function ai(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ci(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function li(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Wt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Wt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Wt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw we("ECDSA");const t=ai(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ci(s,r)}function Fr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const Wr=(s,...e)=>Fr("Key must be ",s,...e);function Ur(s,e,...r){return Fr(`Key for the ${s} algorithm must be `,e,...r)}const Hr=s=>Lr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ft=["CryptoKey"],di=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function ui(s){return typeof s=="object"&&s!==null}function Se(s){if(!ui(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const hi=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ke(s){return Se(s)&&typeof s.kty=="string"}function pi(s){return s.kty!=="oct"&&typeof s.d=="string"}function fi(s){return s.kty!=="oct"&&typeof s.d>"u"}function _i(s){return Ke(s)&&s.kty==="oct"&&typeof s.k=="string"}function gi(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const Gr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=gi(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,Bt.subtle.importKey("jwk",n,...t)},Kr=s=>Re(s);let qe,Ve;const qr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",_t=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await Gr({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},xi={normalizePublicKey:(s,e)=>{if(qr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Kr(r.k):(Ve||(Ve=new WeakMap),_t(Ve,s,r,e))}return Ke(s)?s.k?Re(s.k):(Ve||(Ve=new WeakMap),_t(Ve,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(qr(s)){let r=s.export({format:"jwk"});return r.k?Kr(r.k):(qe||(qe=new WeakMap),_t(qe,s,r,e))}return Ke(s)?s.k?Re(s.k):(qe||(qe=new WeakMap),_t(qe,s,s,e,!0)):s}};async function Vr(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Gr({...s,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const ze=s=>s==null?void 0:s[Symbol.toStringTag],Ut=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},wi=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ke(e)){if(_i(e)&&Ut(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Hr(e))throw new TypeError(Ur(s,e,...ft,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${ze(e)} instances for symmetric algorithms must be of type "secret"`)}},mi=(s,e,r,t)=>{if(t&&Ke(e))switch(r){case"sign":if(pi(e)&&Ut(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(fi(e)&&Ut(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Hr(e))throw new TypeError(Ur(s,e,...ft,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${ze(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function zr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?wi(e,r,t,s):mi(e,r,t,s)}zr.bind(void 0,!1);const Jr=zr.bind(void 0,!0);function yi(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const bi=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function Si(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function vi(s,e,r){if(e=await xi.normalizePublicKey(e,s),Lr(e))return li(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(Wr(e,...ft));return Bt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Wr(e,...ft,"Uint8Array","JSON Web Key"))}const Ei=async(s,e,r,t)=>{const n=await vi(s,e,"verify");hi(s,n);const i=Si(s,n.algorithm);try{return await Bt.subtle.verify(i,n,r,t)}catch{return!1}};async function Ai(s,e,r){if(!Se(s))throw new te("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new te('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new te("JWS Protected Header incorrect type");if(s.payload===void 0)throw new te("JWS Payload missing");if(typeof s.signature!="string")throw new te("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new te("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const w=Re(s.protected);t=JSON.parse(Qe.decode(w))}catch{throw new te("JWS Protected Header is invalid")}if(!di(t,s.header))throw new te("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=yi(te,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new te('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new te('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&bi("algorithms",r.algorithms);if(c&&!c.has(a))throw new Dr('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new te("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new te("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Jr(a,e,"verify"),Ke(e)&&(e=await Vr(e,a))):Jr(a,e,"verify");const u=ri(pt.encode(s.protected??""),pt.encode("."),typeof s.payload=="string"?pt.encode(s.payload):s.payload);let h;try{h=Re(s.signature)}catch{throw new te("Failed to base64url decode the signature")}if(!await Ei(a,e,h,u))throw new $r;let f;if(o)try{f=Re(s.payload)}catch{throw new te("Failed to base64url decode the payload")}else typeof s.payload=="string"?f=pt.encode(s.payload):f=s.payload;const x={payload:f};return s.protected!==void 0&&(x.protectedHeader=t),s.header!==void 0&&(x.unprotectedHeader=s.header),l?{...x,key:e}:x}async function Ii(s,e,r){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new te("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new te("Invalid Compact JWS");const a=await Ai({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Ti=s=>Math.floor(s.getTime()/1e3),jr=60,Yr=jr*60,Ht=Yr*24,Ri=Ht*7,ki=Ht*365.25,Ci=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Xr=s=>{const e=Ci.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*jr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Yr);break;case"day":case"days":case"d":n=Math.round(r*Ht);break;case"week":case"weeks":case"w":n=Math.round(r*Ri);break;default:n=Math.round(r*ki);break}return e[1]==="-"||e[4]==="ago"?-n:n},Zr=s=>s.toLowerCase().replace(/^application\//,""),Ni=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Pi=(s,e,r={})=>{let t;try{t=JSON.parse(Qe.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Zr(s.typ)!==Zr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const x of new Set(u.reverse()))if(!(x in t))throw new he(`missing required "${x}" claim`,t,x,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Ni(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=Xr(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=r,f=Ti(_||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>f+h)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=f-h)throw new Mt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=f-t.iat,w=typeof l=="number"?l:Xr(l);if(x-h>w)throw new Mt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-h)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Oi(s,e,r){var o;const t=await Ii(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:Pi(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Li(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function Di(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Bi)}function Bi(s){return Se(s)}function Qr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Mi{constructor(e){if(this._cached=new WeakMap,!Di(e))throw new $t("JSON Web Key Set malformed");this._jwks=Qr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Li(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Ft;if(c!==1){const l=new Br,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const h of o)try{yield await es(u,h,t)}catch{}},l}return es(this._cached,a,t)}}async function es(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Vr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new $t("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function ts(s){const e=new Mi(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Qr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const $i=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new Mr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new se("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new se("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Fi(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Gt;(typeof navigator>"u"||!((hn=(Rt=navigator.userAgent)==null?void 0:Rt.startsWith)!=null&&hn.call(Rt,"Mozilla/5.0 ")))&&(Gt="jose/v5.10.0");const Kt=Symbol();function Wi(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Ui{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Kt])!==void 0&&(this._cache=r==null?void 0:r[Kt],Wi(r==null?void 0:r[Kt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=ts(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Ft&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Fi()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Gt&&!e.has("User-Agent")&&(e.set("User-Agent",Gt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=$i(this._url,this._timeoutDuration,this._options).then(r=>{this._local=ts(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Hi(s,e){const r=new Ui(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Gi=Re;function Ki(s){if(typeof s!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=Gi(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function qt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function Q(s,e,r=""){const t=qt(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function rs(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Je(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function ss(s,e){Q(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function qi(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Vt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const Vi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function zi(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Ji(s){for(let e=0;e<s.length;e++)s[e]=zi(s[e]);return s}const ns=Vi?s=>s:Ji,is=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ji=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if(Q(s),is)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=ji[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function os(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function gt(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(is)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=os(s.charCodeAt(i)),a=os(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];Q(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function as(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function cs(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Yi=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Xi(s,e,r){return s&e^~s&r}function Zi(s,e,r){return s&e^s&r^e&r}class Qi{constructor(e,r,t,n){O(this,"blockLen");O(this,"outputLen");O(this,"padOffset");O(this,"isLE");O(this,"buffer");O(this,"view");O(this,"finished",!1);O(this,"length",0);O(this,"pos",0);O(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Vt(this.buffer)}update(e){Je(this),Q(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Vt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Je(this),ss(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,je(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let h=o;h<n;h++)r[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Vt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xt=BigInt(2**32-1),ls=BigInt(32);function eo(s,e=!1){return e?{h:Number(s&xt),l:Number(s>>ls&xt)}:{h:Number(s>>ls&xt)|0,l:Number(s&xt)|0}}function to(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=eo(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const ro=(s,e,r)=>s<<r|e>>>32-r,so=(s,e,r)=>e<<r|s>>>32-r,no=(s,e,r)=>e<<r-32|s>>>64-r,io=(s,e,r)=>s<<r-32|e>>>64-r,oo=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ne=new Uint32Array(64);class ao extends Qi{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Ne[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const _=Ne[h-15],f=Ne[h-2],x=me(_,7)^me(_,18)^_>>>3,w=me(f,17)^me(f,19)^f>>>10;Ne[h]=w+Ne[h-7]+x+Ne[h-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const _=me(a,6)^me(a,11)^me(a,25),f=u+_+Xi(a,c,l)+oo[h]+Ne[h]|0,w=(me(t,2)^me(t,13)^me(t,22))+Zi(t,n,i)|0;u=l,l=c,c=a,a=o+f|0,o=i,i=n,n=t,t=f+w|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){je(Ne)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}}class co extends ao{constructor(){super(32);O(this,"A",Ce[0]|0);O(this,"B",Ce[1]|0);O(this,"C",Ce[2]|0);O(this,"D",Ce[3]|0);O(this,"E",Ce[4]|0);O(this,"F",Ce[5]|0);O(this,"G",Ce[6]|0);O(this,"H",Ce[7]|0)}}const lo=as(()=>new co,Yi(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zt=BigInt(0),Jt=BigInt(1);function wt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function ds(s){if(typeof s=="bigint"){if(!bt(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function mt(s){const e=ds(s).toString(16);return e.length&1?"0"+e:e}function us(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?zt:BigInt("0x"+s)}function yt(s){return us(tt(s))}function hs(s){return us(tt(uo(Q(s)).reverse()))}function jt(s,e){ve(e),s=ds(s);const r=gt(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function ps(s,e){return jt(s,e).reverse()}function uo(s){return Uint8Array.from(s)}const bt=s=>typeof s=="bigint"&&zt<=s;function ho(s,e,r){return bt(s)&&bt(e)&&bt(r)&&e<=s&&s<r}function po(s,e,r,t){if(!ho(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function fo(s){let e;for(e=0;s>zt;s>>=Jt,e+=1);return e}const Yt=s=>(Jt<<BigInt(s))-Jt;function _o(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=b=>new Uint8Array(b),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const h=()=>{c.fill(1),l.fill(0),u=0},_=(...b)=>r(l,ke(c,...b)),f=(b=n)=>{l=_(i,b),c=_(),b.length!==0&&(l=_(o,b),c=_())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0;const A=[];for(;b<e;){c=_();const R=c.slice();A.push(R),b+=c.length}return ke(...A)};return(b,A)=>{h(),f(b);let R;for(;!(R=A(x()));)f();return h(),R}}function Xt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function fs(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oe=BigInt(0),ne=BigInt(1),Le=BigInt(2),_s=BigInt(3),gs=BigInt(4),xs=BigInt(5),go=BigInt(7),ws=BigInt(8),xo=BigInt(9),ms=BigInt(16);function pe(s,e){const r=s%e;return r>=oe?r:e+r}function le(s,e,r){let t=s;for(;e-- >oe;)t*=t,t%=r;return t}function ys(s,e){if(s===oe)throw new Error("invert: expected non-zero number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let r=pe(s,e),t=e,n=oe,i=ne;for(;r!==oe;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==ne)throw new Error("invert: does not exist");return pe(n,e)}function Zt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function bs(s,e){const r=(s.ORDER+ne)/gs,t=s.pow(e,r);return Zt(s,t,e),t}function wo(s,e){const r=(s.ORDER-xs)/ws,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return Zt(s,a,e),a}function mo(s){const e=St(s),r=Ss(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+go)/ms;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const h=a.mul(l,n),_=a.mul(l,i),f=a.eql(a.sqr(u),c),x=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(_,h,x);const w=a.eql(a.sqr(u),c),b=a.cmov(l,u,w);return Zt(a,b,c),b}}function Ss(s){if(s<_s)throw new Error("sqrt is not defined for small field");let e=s-ne,r=0;for(;e%Le===oe;)e/=Le,r++;let t=Le;const n=St(s);for(;Es(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return bs;let i=n.pow(t,e);const o=(e+ne)/Le;return function(c,l){if(c.is0(l))return l;if(Es(c,l)!==1)throw new Error("Cannot find square root");let u=r,h=c.mul(c.ONE,i),_=c.pow(l,e),f=c.pow(l,o);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let x=1,w=c.sqr(_);for(;!c.eql(w,c.ONE);)if(x++,w=c.sqr(w),x===u)throw new Error("Cannot find square root");const b=ne<<BigInt(u-x-1),A=c.pow(h,b);u=x,h=c.sqr(A),_=c.mul(_,h),f=c.mul(f,A)}return f}}function yo(s){return s%gs===_s?bs:s%ws===xs?wo:s%ms===xo?mo(s):Ss(s)}const bo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function So(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=bo.reduce((t,n)=>(t[n]="function",t),e);return Xt(s,r),s}function vo(s,e,r){if(r<oe)throw new Error("invalid exponent, negatives unsupported");if(r===oe)return s.ONE;if(r===ne)return e;let t=s.ONE,n=e;for(;r>oe;)r&ne&&(t=s.mul(t,n)),n=s.sqr(n),r>>=ne;return t}function vs(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function Es(s,e){const r=(s.ORDER-ne)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Eo(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Ao{constructor(e,r={}){O(this,"ORDER");O(this,"BITS");O(this,"BYTES");O(this,"isLE");O(this,"ZERO",oe);O(this,"ONE",ne);O(this,"_lengths");O(this,"_sqrt");O(this,"_mod");var o;if(e<=oe)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Eo(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return pe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ne)===ne}neg(e){return pe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return pe(e*e,this.ORDER)}add(e,r){return pe(e+r,this.ORDER)}sub(e,r){return pe(e-r,this.ORDER)}mul(e,r){return pe(e*r,this.ORDER)}pow(e,r){return vo(this,e,r)}div(e,r){return pe(e*ys(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return ys(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=yo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ps(e,this.BYTES):jt(e,this.BYTES)}fromBytes(e,r=!1){Q(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?hs(e):yt(e);if(a&&(c=pe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return vs(this,e)}cmov(e,r,t){return t?r:e}}function St(s,e={}){return new Ao(s,e)}function As(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Is(s){const e=As(s);return e+Math.ceil(e/2)}function Io(s,e,r=!1){Q(s);const t=s.length,n=As(e),i=Is(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?hs(s):yt(s),a=pe(o,e-ne)+ne;return r?ps(a,n):jt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ye=BigInt(0),De=BigInt(1);function vt(s,e){const r=e.negate();return s?r:e}function Ts(s,e){const r=vs(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Rs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Qt(s,e){Rs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Yt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function ks(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,h=a===0,_=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:_,isNegF:f,offsetF:l}}const er=new WeakMap,Cs=new WeakMap;function tr(s){return Cs.get(s)||1}function Ns(s){if(s!==Ye)throw new Error("invalid wNAF")}class To{constructor(e,r){O(this,"BASE");O(this,"ZERO");O(this,"Fn");O(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ye;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Qt(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Qt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:_,offsetF:f}=ks(t,a,o);t=c,u?i=i.add(vt(_,r[f])):n=n.add(vt(h,r[l]))}return Ns(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Qt(e,this.bits);for(let o=0;o<i.windows&&t!==Ye;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=ks(t,o,i);if(t=a,!l){const h=r[c];n=n.add(u?h.negate():h)}}return Ns(t),n}getPrecomputes(e,r,t){let n=er.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),er.set(r,n))),n}cached(e,r,t){const n=tr(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=tr(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Rs(r,this.bits),Cs.set(e,r),er.delete(e)}hasCache(e){return tr(e)!==1}}function Ro(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ye||t>Ye;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function Ps(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return So(e),e}else return St(s,{isLE:r})}function ko(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ye))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Ps(e.p,r.Fp,t),i=Ps(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Co(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Os{constructor(e,r){O(this,"oHash");O(this,"iHash");O(this,"blockLen");O(this,"outputLen");O(this,"finished",!1);O(this,"destroyed",!1);if(rs(e),Q(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),je(n)}update(e){return Je(this),this.iHash.update(e),this}digestInto(e){Je(this),Q(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ls=(s,e,r)=>new Os(s,e).update(r).digest();Ls.create=(s,e)=>new Os(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ds=(s,e)=>(s+(s>=0?e:-e)/Bs)/e;function No(s,e,r){const[[t,n],[i,o]]=e,a=Ds(o*s,r),c=Ds(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const h=l<Ae,_=u<Ae;h&&(l=-l),_&&(u=-u);const f=Yt(Math.ceil(fo(r)/2))+Xe;if(l<Ae||l>=f||u<Ae||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:l,k2neg:_,k2:u}}function rr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function sr(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return wt(r.lowS,"lowS"),wt(r.prehash,"prehash"),r.format!==void 0&&rr(r.format),r}class Po extends Error{constructor(e=""){super(e)}}const Pe={Err:Po,_tlv:{encode:(s,e)=>{const{Err:r}=Pe;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=mt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?mt(n.length/2|128):"";return mt(s)+i+n+e},decode(s,e){const{Err:r}=Pe;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=Pe;if(s<Ae)throw new e("integer: negative integers are not allowed");let r=mt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Pe;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return yt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Pe,n=Q(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Pe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Xe=BigInt(1),Bs=BigInt(2),Et=BigInt(3),Oo=BigInt(4);function Lo(s,e={}){const r=ko("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Xt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=$s(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(F,m,y){const{x:T,y:N}=m.toAffine(),M=t.toBytes(T);if(wt(y,"isCompressed"),y){u();const D=!t.isOdd(N);return ke(Ms(D),M)}else return ke(Uint8Array.of(4),M,t.toBytes(N))}function _(F){Q(F,void 0,"Point");const{publicKey:m,publicKeyUncompressed:y}=l,T=F.length,N=F[0],M=F.subarray(1);if(T===m&&(N===2||N===3)){const D=t.fromBytes(M);if(!t.isValid(D))throw new Error("bad point: is not on curve, wrong x");const $=w(D);let P;try{P=t.sqrt($)}catch(E){const C=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+C)}u();const H=t.isOdd(P);return(N&1)===1!==H&&(P=t.neg(P)),{x:D,y:P}}else if(T===y&&N===4){const D=t.BYTES,$=t.fromBytes(M.subarray(0,D)),P=t.fromBytes(M.subarray(D,D*2));if(!b($,P))throw new Error("bad point: is not on curve");return{x:$,y:P}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${y}`)}const f=e.toBytes||h,x=e.fromBytes||_;function w(F){const m=t.sqr(F),y=t.mul(m,F);return t.add(t.add(y,t.mul(F,i.a)),i.b)}function b(F,m){const y=t.sqr(m),T=w(F);return t.eql(y,T)}if(!b(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,Et),Oo),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,R)))throw new Error("bad curve params: a or b");function k(F,m,y=!1){if(!t.isValid(m)||y&&t.is0(m))throw new Error(`bad point coordinate ${F}`);return m}function L(F){if(!(F instanceof X))throw new Error("Weierstrass Point expected")}function U(F){if(!c||!c.basises)throw new Error("no endo");return No(F,c.basises,n.ORDER)}const G=fs((F,m)=>{const{X:y,Y:T,Z:N}=F;if(t.eql(N,t.ONE))return{x:y,y:T};const M=F.is0();m==null&&(m=M?t.ONE:t.inv(N));const D=t.mul(y,m),$=t.mul(T,m),P=t.mul(N,m);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:D,y:$}}),ae=fs(F=>{if(F.is0()){if(e.allowInfinityPoint&&!t.is0(F.Y))return;throw new Error("bad point: ZERO")}const{x:m,y}=F.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not field elements");if(!b(m,y))throw new Error("bad point: equation left != right");if(!F.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Y(F,m,y,T,N){return y=new X(t.mul(y.X,F),y.Y,y.Z),m=vt(T,m),y=vt(N,y),m.add(y)}const B=class B{constructor(m,y,T){O(this,"X");O(this,"Y");O(this,"Z");this.X=k("x",m),this.Y=k("y",y,!0),this.Z=k("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:y,y:T}=m||{};if(!m||!t.isValid(y)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof B)throw new Error("projective point not allowed");return t.is0(y)&&t.is0(T)?B.ZERO:new B(y,T,t.ONE)}static fromBytes(m){const y=B.fromAffine(x(Q(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return B.fromBytes(gt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return K.createCache(this,m),y||this.multiply(Et),this}assertValidity(){ae(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){L(m);const{X:y,Y:T,Z:N}=this,{X:M,Y:D,Z:$}=m,P=t.eql(t.mul(y,$),t.mul(M,N)),H=t.eql(t.mul(T,$),t.mul(D,N));return P&&H}negate(){return new B(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:y}=i,T=t.mul(y,Et),{X:N,Y:M,Z:D}=this;let $=t.ZERO,P=t.ZERO,H=t.ZERO,S=t.mul(N,N),E=t.mul(M,M),C=t.mul(D,D),I=t.mul(N,M);return I=t.add(I,I),H=t.mul(N,D),H=t.add(H,H),$=t.mul(m,H),P=t.mul(T,C),P=t.add($,P),$=t.sub(E,P),P=t.add(E,P),P=t.mul($,P),$=t.mul(I,$),H=t.mul(T,H),C=t.mul(m,C),I=t.sub(S,C),I=t.mul(m,I),I=t.add(I,H),H=t.add(S,S),S=t.add(H,S),S=t.add(S,C),S=t.mul(S,I),P=t.add(P,S),C=t.mul(M,D),C=t.add(C,C),S=t.mul(C,I),$=t.sub($,S),H=t.mul(C,E),H=t.add(H,H),H=t.add(H,H),new B($,P,H)}add(m){L(m);const{X:y,Y:T,Z:N}=this,{X:M,Y:D,Z:$}=m;let P=t.ZERO,H=t.ZERO,S=t.ZERO;const E=i.a,C=t.mul(i.b,Et);let I=t.mul(y,M),W=t.mul(T,D),q=t.mul(N,$),J=t.add(y,T),z=t.add(M,D);J=t.mul(J,z),z=t.add(I,W),J=t.sub(J,z),z=t.add(y,N);let Z=t.add(M,$);return z=t.mul(z,Z),Z=t.add(I,q),z=t.sub(z,Z),Z=t.add(T,N),P=t.add(D,$),Z=t.mul(Z,P),P=t.add(W,q),Z=t.sub(Z,P),S=t.mul(E,z),P=t.mul(C,q),S=t.add(P,S),P=t.sub(W,S),S=t.add(W,S),H=t.mul(P,S),W=t.add(I,I),W=t.add(W,I),q=t.mul(E,q),z=t.mul(C,z),W=t.add(W,q),q=t.sub(I,q),q=t.mul(E,q),z=t.add(z,q),I=t.mul(W,z),H=t.add(H,I),I=t.mul(Z,z),P=t.mul(J,P),P=t.sub(P,I),I=t.mul(J,W),S=t.mul(Z,S),S=t.add(S,I),new B(P,H,S)}subtract(m){return this.add(m.negate())}is0(){return this.equals(B.ZERO)}multiply(m){const{endo:y}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,N;const M=D=>K.cached(this,D,$=>Ts(B,$));if(y){const{k1neg:D,k1:$,k2neg:P,k2:H}=U(m),{p:S,f:E}=M($),{p:C,f:I}=M(H);N=E.add(I),T=Y(y.beta,S,C,D,P)}else{const{p:D,f:$}=M(m);T=D,N=$}return Ts(B,[T,N])[0]}multiplyUnsafe(m){const{endo:y}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ae||T.is0())return B.ZERO;if(m===Xe)return T;if(K.hasCache(this))return this.multiply(m);if(y){const{k1neg:N,k1:M,k2neg:D,k2:$}=U(m),{p1:P,p2:H}=Ro(B,T,M,$);return Y(y.beta,P,H,N,D)}else return K.unsafe(T,m)}toAffine(m){return G(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Xe?!0:m?m(B,this):K.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Xe?this:m?m(B,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return wt(m,"isCompressed"),this.assertValidity(),f(B,this,m)}toHex(m=!0){return tt(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};O(B,"BASE",new B(i.Gx,i.Gy,t.ONE)),O(B,"ZERO",new B(t.ZERO,t.ONE,t.ZERO)),O(B,"Fp",t),O(B,"Fn",n);let X=B;const V=n.BITS,K=new To(X,e.endo?Math.ceil(V/2):V);return X.BASE.precompute(8),X}function Ms(s){return Uint8Array.of(s?2:3)}function $s(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Do(s,e={}){const{Fn:r}=s,t=e.randomBytes||cs,n=Object.assign($s(s.Fp,r),{seed:Is(r.ORDER)});function i(f){try{const x=r.fromBytes(f);return r.isValidNot0(x)}catch{return!1}}function o(f,x){const{publicKey:w,publicKeyUncompressed:b}=n;try{const A=f.length;return x===!0&&A!==w||x===!1&&A!==b?!1:!!s.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return Io(Q(f,n.seed,"seed"),r.ORDER)}function c(f,x=!0){return s.BASE.multiply(r.fromBytes(f)).toBytes(x)}function l(f){const{secretKey:x,publicKey:w,publicKeyUncompressed:b}=n;if(!qt(f)||"_lengths"in r&&r._lengths||x===w)return;const A=Q(f,void 0,"key").length;return A===w||A===b}function u(f,x,w=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const b=r.fromBytes(f);return s.fromBytes(x).multiply(b).toBytes(w)}const h={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=Co(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:s,utils:h,lengths:n})}function Bo(s,e,r={}){rs(e),Xt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||cs,n=r.hmac||((m,y)=>Ls(e,m,y)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:f}=Do(s,r),x={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*Bs<i.ORDER;function b(m){const y=a>>Xe;return m>y}function A(m,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function R(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(m,y){rr(y);const T=f.signature,N=y==="compact"?T:y==="recovered"?T+1:void 0;return Q(m,N)}class L{constructor(y,T,N){O(this,"r");O(this,"s");O(this,"recovery");if(this.r=A("r",y),this.s=A("s",T),N!=null){if(R(),![0,1,2,3].includes(N))throw new Error("invalid recovery id");this.recovery=N}Object.freeze(this)}static fromBytes(y,T=x.format){k(y,T);let N;if(T==="der"){const{r:P,s:H}=Pe.toSig(Q(y));return new L(P,H)}T==="recovered"&&(N=y[0],T="compact",y=y.subarray(1));const M=f.signature/2,D=y.subarray(0,M),$=y.subarray(M,M*2);return new L(o.fromBytes(D),o.fromBytes($),N)}static fromHex(y,T){return this.fromBytes(gt(y),T)}assertRecovery(){const{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new L(this.r,this.s,y)}recoverPublicKey(y){const{r:T,s:N}=this,M=this.assertRecovery(),D=M===2||M===3?T+a:T;if(!i.isValid(D))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const $=i.toBytes(D),P=s.fromBytes(ke(Ms((M&1)===0),$)),H=o.inv(D),S=G(Q(y,void 0,"msgHash")),E=o.create(-S*H),C=o.create(N*H),I=s.BASE.multiplyUnsafe(E).add(P.multiplyUnsafe(C));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return b(this.s)}toBytes(y=x.format){if(rr(y),y==="der")return gt(Pe.hexFromSig(this));const{r:T,s:N}=this,M=o.toBytes(T),D=o.toBytes(N);return y==="recovered"?(R(),ke(Uint8Array.of(this.assertRecovery()),M,D)):ke(M,D)}toHex(y){return tt(this.toBytes(y))}}const U=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const T=yt(y),N=y.length*8-c;return N>0?T>>BigInt(N):T},G=r.bits2int_modN||function(y){return o.create(U(y))},ae=Yt(c);function Y(m){return po("num < 2^"+c,m,Ae,ae),o.toBytes(m)}function X(m,y){return Q(m,void 0,"message"),y?Q(e(m),void 0,"prehashed message"):m}function V(m,y,T){const{lowS:N,prehash:M,extraEntropy:D}=sr(T,x);m=X(m,M);const $=G(m),P=o.fromBytes(y);if(!o.isValidNot0(P))throw new Error("invalid private key");const H=[Y(P),Y($)];if(D!=null&&D!==!1){const I=D===!0?t(f.secretKey):D;H.push(Q(I,void 0,"extraEntropy"))}const S=ke(...H),E=$;function C(I){const W=U(I);if(!o.isValidNot0(W))return;const q=o.inv(W),J=s.BASE.multiply(W).toAffine(),z=o.create(J.x);if(z===Ae)return;const Z=o.create(q*o.create(E+z*P));if(Z===Ae)return;let We=(J.x===z?0:2)|Number(J.y&Xe),pn=Z;return N&&b(Z)&&(pn=o.neg(Z),We^=1),new L(z,pn,w?void 0:We)}return{seed:S,k2sig:C}}function K(m,y,T={}){const{seed:N,k2sig:M}=V(m,y,T);return _o(e.outputLen,o.BYTES,n)(N,M).toBytes(T.format)}function B(m,y,T,N={}){const{lowS:M,prehash:D,format:$}=sr(N,x);if(T=Q(T,void 0,"publicKey"),y=X(y,D),!qt(m)){const P=m instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}k(m,$);try{const P=L.fromBytes(m,$),H=s.fromBytes(T);if(M&&P.hasHighS())return!1;const{r:S,s:E}=P,C=G(y),I=o.inv(E),W=o.create(C*I),q=o.create(S*I),J=s.BASE.multiplyUnsafe(W).add(H.multiplyUnsafe(q));return J.is0()?!1:o.create(J.x)===S}catch{return!1}}function F(m,y,T={}){const{prehash:N}=sr(T,x);return y=X(y,N),L.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:f,Point:s,sign:K,verify:B,recoverPublicKey:F,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Mo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Fs=BigInt(2);function $o(s){const e=nr.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,h=le(u,r,e)*u%e,_=le(h,r,e)*u%e,f=le(_,Fs,e)*l%e,x=le(f,n,e)*f%e,w=le(x,i,e)*x%e,b=le(w,a,e)*w%e,A=le(b,c,e)*b%e,R=le(A,a,e)*w%e,k=le(R,r,e)*u%e,L=le(k,o,e)*x%e,U=le(L,t,e)*l%e,G=le(U,Fs,e);if(!ir.eql(ir.sqr(G),s))throw new Error("Cannot find square root");return G}const ir=St(nr.p,{sqrt:$o}),Fo=Bo(Lo(nr,{Fp:ir,endo:Mo}),lo),Wo=BigInt(0),rt=BigInt(1),Uo=BigInt(2),Ho=BigInt(7),Go=BigInt(256),Ko=BigInt(113),Ws=[],Us=[],Hs=[];for(let s=0,e=rt,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],Ws.push(2*(5*t+r)),Us.push((s+1)*(s+2)/2%64);let n=Wo;for(let i=0;i<7;i++)e=(e<<rt^(e>>Ho)*Ko)%Go,e&Uo&&(n^=rt<<(rt<<BigInt(i))-rt);Hs.push(n)}const Gs=to(Hs,!0),qo=Gs[0],Vo=Gs[1],Ks=(s,e,r)=>r>32?no(s,e,r):ro(s,e,r),qs=(s,e,r)=>r>32?io(s,e,r):so(s,e,r);function zo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=Ks(l,u,1)^r[a],_=qs(l,u,1)^r[a+1];for(let f=0;f<50;f+=10)s[o+f]^=h,s[o+f+1]^=_}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=Us[o],c=Ks(n,i,a),l=qs(n,i,a),u=Ws[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=qo[t],s[1]^=Vo[t]}je(r)}class or{constructor(e,r,t,n=!1,i=24){O(this,"state");O(this,"pos",0);O(this,"posOut",0);O(this,"finished",!1);O(this,"state32");O(this,"destroyed",!1);O(this,"blockLen");O(this,"suffix");O(this,"outputLen");O(this,"enableXOF",!1);O(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=qi(this.state)}clone(){return this._cloneInto()}keccak(){ns(this.state32),zo(this.state32,this.rounds),ns(this.state32),this.posOut=0,this.pos=0}update(e){Je(this),Q(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Je(this,!1),Q(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ss(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,je(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new or(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Vs=((s,e,r,t={})=>as(()=>new or(e,s,r),t))(1,136,32),Jo=60;class jo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Hi(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Jo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Oi(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ki(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
7
- ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Vs(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Yo(a),l=c.slice(0,32),u=c.slice(32,64),h=c[64],_=h>=27?h-27:h,w=new Fo.Signature(zs(l),zs(u)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),b=Vs(w);return"0x"+tt(b.slice(12))}}function Yo(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function zs(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Xo=3e4,Zo=1e3;class Qo{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,Zo*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Xo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const ea=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i];function ar(){return typeof window>"u"?void 0:window}function ta(){const s=ar();return s==null?void 0:s.__crossx}function ra(s){return s==="ios"||s==="android"?s:null}function sa(){const s=ar();if(!s)return!1;const e=s.__crossxRNBridge;return e!=null&&e.isInstalled?!0:s.__CROSSX_BRIDGE_INITIALIZED__===!0||s.__CROSSX_RN_BRIDGE_READY__===!0}function Js(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of ea){const r=e.exec(s);if(r)return r[1]??null}}function st(){const s=ta();if(s!=null&&s.browser)return{version:s.version??null,platform:ra(s.platform),detectedBy:"marker"};if(sa())return{version:Js()??null,platform:null,detectedBy:"bridge"};const e=Js();return e!==void 0?{version:e,platform:null,detectedBy:"user-agent"}:null}function na(){return st()!==null}function ia(s=3e3){const e=st();return e?Promise.resolve(e):ar()?new Promise(r=>{const t=Date.now(),n=setInterval(()=>{const i=st();if(i){clearInterval(n),r(i);return}Date.now()-t>=s&&(clearInterval(n),r(null))},50)}):Promise.resolve(null)}const oa=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"]),aa="crossx://oauth-callback";class Be{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(d.log("[CROSSx] OAuth 대기 중단 —",e),r(e))}static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Be.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Be.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Be.generateRandom16Hex(),l=Be.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",h=encodeURIComponent(window.location.origin);let _=`${e.authUrl}${u}state=${c}&nonce=${l}&origin=${h}`;const f=st();f&&!_.includes("redirectUrl=")&&(_+=`&redirectUrl=${encodeURIComponent(aa)}`,d.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:f.detectedBy,appVersion:f.version??"(unknown)",platform:f.platform??"(unknown)"})),d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const x=window.open(_,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),G(),t(new Error("Authentication timeout"))},5*60*1e3),b=10,A=30;let R=0,k=null;const L=()=>{clearInterval(U),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+A+"초간 대기합니다"),k=setTimeout(()=>{G(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},A*1e3)},U=setInterval(()=>{R++;try{if(!x.closed)return;const Y=typeof document<"u"&&document.hasFocus();R<=b&&!Y?L():(G(),t(new Error("로그인이 취소되었습니다")))}catch{L()}},1e3),G=()=>{this.abortPending=null,clearTimeout(w),clearInterval(U),k&&clearTimeout(k),window.removeEventListener("message",ae)},ae=Y=>{if(!oa.has(Y.origin))return;G();const X=typeof Y.data.status=="string",V=X?Y.data.data??{}:Y.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:X?"wrapped":"flat",status:X?Y.data.status:"(flat)"});const K=(V==null?void 0:V.state)??Y.data.state;if(!K||K!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(X&&Y.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",V==null?void 0:V.error),t(new Error((V==null?void 0:V.error)||"Authentication failed"));return}if(!X&&(V!=null&&V.error)){d.error("[CROSSx] OAuth 실패:",V.error),t(new Error(V.error||"Authentication failed"));return}const B=V==null?void 0:V.idToken,F=V==null?void 0:V.accessToken,m=F??B,y=(V==null?void 0:V.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!F,hasIdToken:!!B,hasEmail:!!y}),!m){d.error("[CROSSx] 토큰을 찾을 수 없음:",Y.data),t(new Error("Token not found in response"));return}const T={token:m,email:y},N=M=>{Be.verifyIdTokenNonce(M,l).then(()=>r(T)).catch(D=>{d.error("[CROSSx] nonce 검증 실패:",D),t(D instanceof Error?D:new Error("nonce verification failed"))})};F?F.split(".").length===3?N(F):B?N(B):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(T)):B?N(B):t(new Error("Token not found in response"))};this.abortPending=Y=>{G(),t(new Error(Y))},window.addEventListener("message",ae)})}}const nt="crossx_wallet_data",Ze="crossx_mock_pin_hash";class ca{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(nt)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(nt);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(nt,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Ze,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(nt);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ze);return r&&r!==e?!1:(r||await this.storage.set(Ze,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(p.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ze);if(n&&t&&n!==t)throw new g(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ze,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new g(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new g(p.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(nt,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ze,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Me{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Sr))return e;const r=!e||this.tokenStore.isExpiringSoon(Sr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,h;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const f=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(f&&typeof f.code=="number"){if(f.code<0||f.code>=400){const x=f.message||f.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:f.code,message:x,url:o,method:e});const w=Me.mapGatewayError(f.code,f.data);if(w===p.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(w===p.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(p.USER_NOT_FOUND,Me.getGatewayErrorMessage(f.code,x));const b=w===p.AUTH_NOT_AUTHENTICATED?p.SESSION_EXPIRED:w,A=b===p.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Me.getGatewayErrorMessage(f.code,x),R=f.data;let k;throw w===p.PIN_LOCKED?k=Me.extractLockDetails(R):w===p.ADDRESS_LIMIT_EXCEEDED?k={limit:ot,raw:R}:k=R??void 0,new g(b,A,k)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:f.code,url:o,method:e}),f.data??f}return f}catch(_){if(_ instanceof g)throw _;const f=((l=_.response)==null?void 0:l.status)??_.status;if((f===401||f===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${f} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const x=_.response.data,w=x.message||x.data||"API 요청에 실패했습니다",b=x.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:b,message:w,url:o,method:e,status:(h=_.response)==null?void 0:h.status}),new g(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${b}): ${w}`)}throw _}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new g(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new g(p.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 g(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new g(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new g(p.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new g(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10007:return p.BROADCAST_FAILED;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10004:return p.WALLET_ALREADY_EXISTS;case-10005:return p.WALLET_NOT_FOUND;case-10011:return p.WALLET_NOT_FOUND;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10013:return p.WITHDRAW_FAILED;case-10033:return p.USER_NOT_FOUND;case-10036:return p.ADDRESS_LIMIT_EXCEEDED;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10025:return p.INVALID_APP_TYPE;case-10028:return Me.hasLockInfo(r)?p.PIN_LOCKED:p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10032:return p.PIN_REPEATED_PATTERN;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10040:return p.HMAC_REQUIRED;case-10041:return p.HMAC_VERIFICATION_FAILED;default:return p.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 ${ot} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class la{constructor(e,r,t,n=()=>{},i=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,this.getAppName=i,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(o,a)=>e.prepare(o,a)),e.migrateWallet&&(this.migrateWallet=(o,a)=>e.migrateWallet(o,a)),e.verifyPin&&(this.verifyPin=o=>e.verifyPin(o)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(o,a)=>e.verifyRecoveryPin(o,a))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();const c=await a.signMessage({chainId:r,message:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){this.assertBridgeSessionActive();const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return this.assertBridgeSessionActive(),{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,dappName:this.getAppName()})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class it{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=it.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?mn:wn;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 g(it.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=it.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new g(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(ct).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const js="__crossx-confirm-style",re="__crossx-confirm-overlay",da={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 Ys(s,e){const r=da[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary,contentHigh:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const ua=`
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"},Rn={ko:Tn,en:Rr};function be(s="en",e){return Rn[s]??Rr}function kn(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const kr="crossx_access_token",Cr="crossx_refresh_token",Nr="crossx_user_info",Tt=class Tt{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${u}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new g(p.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o,legacyOauthServiceUrl:a}=this.config,c=kn(this.getLocale()),l=f=>{const x=`${f}${i}`,w=x.includes("?")?"&":"?";return`${x}${w}locale=${c}`},u=l(o),h=a?l(a):void 0;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const _=await this.oauth.openAuth({authUrl:u,...h?{legacyAuthUrl:h}:{},expectedOrigin:new URL(o).origin});r=_.token,t=_.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new g(p.OAUTH_POPUP_BLOCKED,i):new g(p.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const h=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=h.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new g(p.AUTH_FAILED,"Access token 검증 실패");const h=u.payload;r={id:h.sub,email:h.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new g(p.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:h,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let f,x,w;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),x=(i=A.firebase)==null?void 0:i.sign_in_provider;const R=((o=A.firebase)==null?void 0:o.identities)??{};w=A.email??((a=R.email)==null?void 0:a[0]),x==="google.com"?f=(c=R["google.com"])==null?void 0:c[0]:x==="apple.com"&&(f=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!f,"email:",w??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(h){const A=this.crypto.decodeJWT(h);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const R=await this.crypto.verifyJWT(h);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const C=R.payload,D=C.email??w??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",C.email??"(없음)","/ Firebase JWT:",w??"(없음)","/ OAuth 콜백:",r??"(없음)","→",D??"(없음)"),t={id:C.sub,email:D,signInProvider:x,providerSub:f},this.tokenStore.set(h),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,h),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??r,signInProvider:x,providerSub:f},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const b=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,b),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new g(p.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new g(p.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof g&&e.code===p.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=Tt.REFRESH_RELOGIN_CODES.has(c.code);throw new g(u?p.SESSION_EXPIRED:p.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new g(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof g&&t.code===p.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof g&&e.code===p.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Nr);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(kr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Cr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Nr),await this.storage.remove(kr),await this.storage.remove(Cr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof g&&i.code===p.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(i.code===p.PROJECT_NOT_REGISTERED||i.code===p.PROJECT_ID_MISSING||i.code===p.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};Tt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Nt=Tt;class Cn{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Nn{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new g(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Ot{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class On{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new g(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Pn{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function Ln(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class fe{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await fe.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=fe.getBridge(),!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new g(p.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=Ln(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new g(p.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0,a=n.provider==="google"||n.provider==="apple"?n.provider:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:o,walletProvider:a}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new g(p.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new g(p.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 g(p.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof g)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new g(p.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new g(p.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new g(p.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof g?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new g(p.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new g(p.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new g(p.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 g(p.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof g?r:(d.warn("[RNBridge] Session restore Firebase token request failed",r),new g(p.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 g(p.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var lt={environment:"production"};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 Dn(s){const e=s.environment,r=e&&e in He?He[e]:null;if(!r)return null;const t=s.overrides;if(!t)return r;const n={...r};for(const[i,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(n[i]=o);return n}function Pt(){try{if(typeof lt<"u"){const s=typeof lt=="string"?JSON.parse(lt):lt,e=Dn(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in He)return He[s]}catch{}return He.production}function Or(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Bn(s,e=kt){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Sr),n=r/t,o=(r%t).toString().padStart(Sr,"0"),a=Or(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function dt(s,e,r,t=kt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=Or(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Mn(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==br)throw new g(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${br} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function $n(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Fn(s,e){const r=Wn(e);if(s==="0"){if(r!==void 0&&r!==0)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Wn(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Ge{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new g(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){var c,l;if((l=(c=this.deps).isRNBridgeMode)!=null&&l.call(c))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((u,h)=>{i=u,o=h});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const h=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!h)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(h),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const u=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async h=>{this.deps.pinStore.set(h);try{return await this.deps.walletProvider.verifyPin(h)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(_){if(this.deps.pinStore.clear(),_ instanceof g){if(_.code===p.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(_.code===p.PIN_INVALID)return{ok:!1,error:_.message};if(_.code===p.PIN_LOCKED)return Ge.buildPinLockedResult(_,a)}throw _}}});if(!u)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(u),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(u){if(u instanceof g&&(u.code===p.AUTH_NOT_AUTHENTICATED||u.code===p.AUTH_TOKEN_EXPIRED||u.code===p.SESSION_EXPIRED)&&u.code!==p.SESSION_EXPIRED){const h=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:h.session_alert_title,message:h.alert_session_expired,email:_?this.deps.maskEmail(_,h.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(u),u}throw o(u),u}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Ge.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof g&&(t=Ge.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===p.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===p.PIN_INVALID)return{errorMessage:e.message};if(e.code===p.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Ge.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Un{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new g(p.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function Hn(s){return s==="google"||s==="apple"}class Gn{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Hn(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof g&&r.code===p.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof g&&r.code===p.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof g)||r.code!==p.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new g(p.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new g(p.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Kn{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const h=o.find(_=>_.address.toLowerCase()===r.toLowerCase());h?c=h:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(h=>h.index===e)??o[0]:c=o[0];l?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const u=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,u?{walletName:t}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class qn{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const h=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!h){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(h.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const _=h.pinStatus;if(o=_.maxAttempts,i=o-_.remainingAttempts,_.remainingAttempts===0&&_.lockExpiresAt){const f=_.lockExpiresAt*1e3,x=Math.max(1,Math.round((f-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${w}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(h){if(!(h instanceof g))throw h;if(h.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const _=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:_.session_alert_title,message:_.alert_session_expired,email:f?this.deps.maskEmail(f,_.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),h}if(h.code===p.MIGRATION_PIN_LOCKED){const _=h.details;if(o=(_==null?void 0:_.maxAttempts)??5,(_==null?void 0:_.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const f=((_==null?void 0:_.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((f-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",h),h}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof g&&u.code===p.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof g&&u.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const h=be(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:h.session_alert_title,message:h.alert_session_expired,email:_?this.deps.maskEmail(_,h.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const w=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",w.address),w}catch(w){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",w),w}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Vn{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,h,_]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=h,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const f=_;if(f){const x=yr;c.maxFeePerGas=`0x${(BigInt(f)+BigInt(x)).toString(16)}`,c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=wn,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=yr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class zn{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Jn(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class jn{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e,r){var n,i,o,a,c;const t={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:Jn((a=e.user)==null?void 0:a.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(t),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...r?{source:r}:{}})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Yn{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 g(p.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 Xn{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new g(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new g(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Zn{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",o);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(o);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new g(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof g&&r.code===p.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new g(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function Pr(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Qn{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new g(p.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new g(p.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new g(p.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new g(p.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=Pr(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof g?c:new g(p.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(Pr(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new g(p.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof g?i:new g(p.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof g&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:p.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:p.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:p.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:p.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new g(n.code,n.message)}}function Lt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Fe=class Fe extends Pn{constructor(e,r,t,n,i,o,a,c,l,u,h){var _,f;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._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&&Tr(e.logger),this.confirmation=l,this.pinStore=h??new Ot,this.stateManager=new jn({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:w,walletName:b})=>{const A={address:x,index:w};b!==void 0&&(A.walletName=b),this.emit("addressChanged",A)},emitAuthChanged:({isAuthenticated:x,address:w,userId:b,source:A})=>{this.emit("authChanged",{isAuthenticated:x,address:w,userId:b,...A?{source:A}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Fe.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ge({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Lt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new Un({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Kn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,w,b)=>this.setActiveWallet(x,w,b)}),this.migrationOrchestrator=new qn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,w)=>this.migrateWalletUseCase.execute(x,w),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Lt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new Vn({getActiveAddress:()=>this.address,estimateGas:(x,w)=>this.estimateGas(x,w),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,w,b)=>this.jsonRpc.call(x,w,b)}),this.signatureVerifier=new zn(this.crypto),this.addressResolverService=new Yn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Xn({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Zn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,w)=>this.setActiveWallet(x,w),showWalletCreated:()=>{var x,w;return((w=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:w.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Qn({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Gn({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:x=>{this._isRecoveringSession=x},setAuthenticated:x=>{this.authenticated=x},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:x=>this.signInUseCase.execute(x),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:x=>this.confirmation.showSessionAlert(x),clearAuthState:()=>this.clearAuthState(),applyAuthResult:x=>this.applyAuthResult(x),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:Lt}),this.chainRegistry=u,this.jsonRpc=new On(u,i),this.signInUseCase=new Nt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new Cn(this.internalConfig,t,c),this.migrateWalletUseCase=new Nn(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(f=a.setTokenRefresher)==null||f.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.3.10-beta.7 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=Pt();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=n.legacyOauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Fe.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),u=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,u?{walletName:u}:void 0);else try{await this.loadWalletAfterAuth(o,a,u)}catch(h){if(h instanceof g&&h.code===p.PIN_CANCELLED)d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(h instanceof g&&(h.code===p.SESSION_EXPIRED||h.code===p.AUTH_NOT_AUTHENTICATED||h.code===p.USER_NOT_FOUND))d.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",h.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw h}}return this.initialized=!0,d.info("[CROSSx SDK] v2.3.10-beta.7 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new g(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!fe.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),d.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.10-beta.7",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new fe({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.3.10-beta.7",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof g&&r.code===p.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession()||(this._isAuthenticatedViaRNBridge=!0,await this.signInUseCase.hasValidStoredAccessToken()))return null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(d.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new g(p.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw d.error("[CROSSx] Bridge session restore token request failed:",e),new g(p.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return fe.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&d.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let t=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:vn(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new g(p.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(t);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof g?n:new g(p.AUTH_FAILED,"로그인에 실패했습니다",n)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof g&&i.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){var t,n;if(this.ensureInitialized(),this.authenticated)throw new g(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r,"external"),(n=(t=this.oauth).cancelPending)==null||n.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof g?i:new g(p.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c);return{...r,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:i}}catch(i){throw i instanceof g&&i.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),i}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new g(p.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 g?t:new g(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=fe.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new g(p.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 g&&t.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof g&&t.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof g?r:new g(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof g?e:new g(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof g?r:new g(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(be(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const n=fe.getBridge();if(n!=null&&n.signMessage){const o=await n.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:o.signature,message:r,address:this.address??""}}if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const i=await this.resolveAddress(t==null?void 0:t.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:i.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:i.address},execute:a=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,i.address)});return this.signatureVerifier.verifySignatureSigner(r,o.signature,i.address),{chainId:e,signature:o.signature,message:r,address:i.address}}catch(o){throw o instanceof g?o:new g(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}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 g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Fn(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Mn(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof g?i:new g(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(Fe.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return $n(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(p.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 g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=Ct(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const h=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return h.txHash??h.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,bn).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof g)throw o;const a=o instanceof Error?o.message:String(o);throw new g(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??gn,i=xn,o=t.timeoutMs??mr,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var w,b;if(this._isAuthenticatedViaRNBridge){const A=fe.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??_n,l=i??((b=this._config.receiptPolling)==null?void 0:b.timeoutMs)??mr,u=Ct(e),h=r.from??"";let _,f;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{_=A;const R=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),C=r.value?BigInt(r.value):0n,D=dt(r.value,u.symbol,u.decimals,this._config.displayDecimals),H=dt("0x"+R.toString(16),u.symbol,u.decimals,this._config.displayDecimals),K=dt("0x"+(C+R).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:D,fees:H,total:K,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(f=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:h,to:r.to,amount:dt(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:r.to},x),f)throw f;return{chainId:e,txHash:a,receipt:_}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(p.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(p.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(p.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(p.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 g(p.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 g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(p.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Bn(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(p.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new Ir(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(p.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=fe.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){d.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,r){this.stateManager.applyAuthResult(e,r)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Tr(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Fe.WALLET_PREF_KEY="wallet_preference",Fe.OFFCHAIN_CHAIN_ID="0";let ut=Fe;class ei{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Dt="crossx-sdk",ti=1,_e="data",Pe="keys",ht="aes-primary",ri=12;class Lr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,ti);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Pe)||i.createObjectStore(Pe)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Pe,ht);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(Pe,ht,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Dt)return null;try{const e=await this.openDB(Dt),r=e.transaction([Pe,_e],"readonly"),t=r.objectStore(Pe).get(ht),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(_e).getAll(),o=r.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Pe,ht,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Dt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(ri);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(_e,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Bt=crypto,Dr=s=>s instanceof CryptoKey,pt=new TextEncoder,Qe=new TextDecoder;function si(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const ni=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ni(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class te extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}te.code="ERR_JOSE_GENERIC";class he extends te{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Mt extends te{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Mt.code="ERR_JWT_EXPIRED";class Br extends te{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Br.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends te{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class ii extends te{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}ii.code="ERR_JWE_DECRYPTION_FAILED";class oi extends te{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}oi.code="ERR_JWE_INVALID";class Q extends te{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Q.code="ERR_JWS_INVALID";class xe extends te{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class ai extends te{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}ai.code="ERR_JWK_INVALID";class $t extends te{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}$t.code="ERR_JWKS_INVALID";class Ft extends te{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Ft.code="ERR_JWKS_NO_MATCHING_KEY";class Mr extends te{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Mr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class $r extends te{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}$r.code="ERR_JWKS_TIMEOUT";class Fr extends te{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Fr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function et(s,e){return s.name===e}function Wt(s){return parseInt(s.name.slice(4),10)}function ci(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function li(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function di(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Wt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Wt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Wt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw we("ECDSA");const t=ci(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}li(s,r)}function Wr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const Ur=(s,...e)=>Wr("Key must be ",s,...e);function Hr(s,e,...r){return Wr(`Key for the ${s} algorithm must be `,e,...r)}const Gr=s=>Dr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ft=["CryptoKey"],ui=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function hi(s){return typeof s=="object"&&s!==null}function Se(s){if(!hi(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const pi=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ke(s){return Se(s)&&typeof s.kty=="string"}function fi(s){return s.kty!=="oct"&&typeof s.d=="string"}function _i(s){return s.kty!=="oct"&&typeof s.d>"u"}function gi(s){return Ke(s)&&s.kty==="oct"&&typeof s.k=="string"}function xi(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const Kr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=xi(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,Bt.subtle.importKey("jwk",n,...t)},qr=s=>Re(s);let qe,Ve;const Vr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",_t=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await Kr({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},wi={normalizePublicKey:(s,e)=>{if(Vr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?qr(r.k):(Ve||(Ve=new WeakMap),_t(Ve,s,r,e))}return Ke(s)?s.k?Re(s.k):(Ve||(Ve=new WeakMap),_t(Ve,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Vr(s)){let r=s.export({format:"jwk"});return r.k?qr(r.k):(qe||(qe=new WeakMap),_t(qe,s,r,e))}return Ke(s)?s.k?Re(s.k):(qe||(qe=new WeakMap),_t(qe,s,s,e,!0)):s}};async function zr(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Kr({...s,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const ze=s=>s==null?void 0:s[Symbol.toStringTag],Ut=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},mi=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ke(e)){if(gi(e)&&Ut(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Gr(e))throw new TypeError(Hr(s,e,...ft,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${ze(e)} instances for symmetric algorithms must be of type "secret"`)}},yi=(s,e,r,t)=>{if(t&&Ke(e))switch(r){case"sign":if(fi(e)&&Ut(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(_i(e)&&Ut(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Gr(e))throw new TypeError(Hr(s,e,...ft,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${ze(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${ze(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${ze(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Jr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?mi(e,r,t,s):yi(e,r,t,s)}Jr.bind(void 0,!1);const jr=Jr.bind(void 0,!0);function bi(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const Si=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function vi(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function Ei(s,e,r){if(e=await wi.normalizePublicKey(e,s),Dr(e))return di(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(Ur(e,...ft));return Bt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Ur(e,...ft,"Uint8Array","JSON Web Key"))}const Ai=async(s,e,r,t)=>{const n=await Ei(s,e,"verify");pi(s,n);const i=vi(s,n.algorithm);try{return await Bt.subtle.verify(i,n,r,t)}catch{return!1}};async function Ii(s,e,r){if(!Se(s))throw new Q("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new Q('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new Q("JWS Protected Header incorrect type");if(s.payload===void 0)throw new Q("JWS Payload missing");if(typeof s.signature!="string")throw new Q("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new Q("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const w=Re(s.protected);t=JSON.parse(Qe.decode(w))}catch{throw new Q("JWS Protected Header is invalid")}if(!ui(t,s.header))throw new Q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=bi(Q,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Q('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&Si("algorithms",r.algorithms);if(c&&!c.has(a))throw new Br('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new Q("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new Q("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,jr(a,e,"verify"),Ke(e)&&(e=await zr(e,a))):jr(a,e,"verify");const u=si(pt.encode(s.protected??""),pt.encode("."),typeof s.payload=="string"?pt.encode(s.payload):s.payload);let h;try{h=Re(s.signature)}catch{throw new Q("Failed to base64url decode the signature")}if(!await Ai(a,e,h,u))throw new Fr;let f;if(o)try{f=Re(s.payload)}catch{throw new Q("Failed to base64url decode the payload")}else typeof s.payload=="string"?f=pt.encode(s.payload):f=s.payload;const x={payload:f};return s.protected!==void 0&&(x.protectedHeader=t),s.header!==void 0&&(x.unprotectedHeader=s.header),l?{...x,key:e}:x}async function Ti(s,e,r){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new Q("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new Q("Invalid Compact JWS");const a=await Ii({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Ri=s=>Math.floor(s.getTime()/1e3),Yr=60,Xr=Yr*60,Ht=Xr*24,ki=Ht*7,Ci=Ht*365.25,Ni=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Zr=s=>{const e=Ni.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Yr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Xr);break;case"day":case"days":case"d":n=Math.round(r*Ht);break;case"week":case"weeks":case"w":n=Math.round(r*ki);break;default:n=Math.round(r*Ci);break}return e[1]==="-"||e[4]==="ago"?-n:n},Qr=s=>s.toLowerCase().replace(/^application\//,""),Oi=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Pi=(s,e,r={})=>{let t;try{t=JSON.parse(Qe.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Qr(s.typ)!==Qr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const x of new Set(u.reverse()))if(!(x in t))throw new he(`missing required "${x}" claim`,t,x,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Oi(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=Zr(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=r,f=Ri(_||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>f+h)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=f-h)throw new Mt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=f-t.iat,w=typeof l=="number"?l:Zr(l);if(x-h>w)throw new Mt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-h)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Li(s,e,r){var o;const t=await Ti(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:Pi(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Di(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function Bi(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Mi)}function Mi(s){return Se(s)}function es(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class $i{constructor(e){if(this._cached=new WeakMap,!Bi(e))throw new $t("JSON Web Key Set malformed");this._jwks=es(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Di(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Ft;if(c!==1){const l=new Mr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const h of o)try{yield await ts(u,h,t)}catch{}},l}return ts(this._cached,a,t)}}async function ts(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await zr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new $t("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function rs(s){const e=new $i(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>es(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Fi=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new $r:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new te("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new te("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Wi(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Gt;(typeof navigator>"u"||!((pn=(Rt=navigator.userAgent)==null?void 0:Rt.startsWith)!=null&&pn.call(Rt,"Mozilla/5.0 ")))&&(Gt="jose/v5.10.0");const Kt=Symbol();function Ui(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Hi{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Kt])!==void 0&&(this._cache=r==null?void 0:r[Kt],Ui(r==null?void 0:r[Kt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=rs(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Ft&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Wi()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Gt&&!e.has("User-Agent")&&(e.set("User-Agent",Gt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Fi(this._url,this._timeoutDuration,this._options).then(r=>{this._local=rs(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Gi(s,e){const r=new Hi(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Ki=Re;function qi(s){if(typeof s!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=Ki(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function qt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function X(s,e,r=""){const t=qt(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function ss(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Je(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function ns(s,e){X(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Vi(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function je(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Vt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const zi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ji(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function ji(s){for(let e=0;e<s.length;e++)s[e]=Ji(s[e]);return s}const is=zi?s=>s:ji,os=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Yi=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if(X(s),os)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Yi[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function as(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function gt(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(os)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=as(s.charCodeAt(i)),a=as(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];X(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function cs(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function ls(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Xi=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Zi(s,e,r){return s&e^~s&r}function Qi(s,e,r){return s&e^s&r^e&r}class eo{constructor(e,r,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Vt(this.buffer)}update(e){Je(this),X(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Vt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Je(this),ns(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,je(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let h=o;h<n;h++)r[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Vt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Ce=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xt=BigInt(2**32-1),ds=BigInt(32);function to(s,e=!1){return e?{h:Number(s&xt),l:Number(s>>ds&xt)}:{h:Number(s>>ds&xt)|0,l:Number(s&xt)|0}}function ro(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=to(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const so=(s,e,r)=>s<<r|e>>>32-r,no=(s,e,r)=>e<<r|s>>>32-r,io=(s,e,r)=>e<<r-32|s>>>64-r,oo=(s,e,r)=>s<<r-32|e>>>64-r,ao=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ne=new Uint32Array(64);class co extends eo{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Ne[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const _=Ne[h-15],f=Ne[h-2],x=me(_,7)^me(_,18)^_>>>3,w=me(f,17)^me(f,19)^f>>>10;Ne[h]=w+Ne[h-7]+x+Ne[h-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const _=me(a,6)^me(a,11)^me(a,25),f=u+_+Zi(a,c,l)+ao[h]+Ne[h]|0,w=(me(t,2)^me(t,13)^me(t,22))+Qi(t,n,i)|0;u=l,l=c,c=a,a=o+f|0,o=i,i=n,n=t,t=f+w|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){je(Ne)}destroy(){this.set(0,0,0,0,0,0,0,0),je(this.buffer)}}class lo extends co{constructor(){super(32);P(this,"A",Ce[0]|0);P(this,"B",Ce[1]|0);P(this,"C",Ce[2]|0);P(this,"D",Ce[3]|0);P(this,"E",Ce[4]|0);P(this,"F",Ce[5]|0);P(this,"G",Ce[6]|0);P(this,"H",Ce[7]|0)}}const uo=cs(()=>new lo,Xi(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zt=BigInt(0),Jt=BigInt(1);function wt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function us(s){if(typeof s=="bigint"){if(!bt(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function mt(s){const e=us(s).toString(16);return e.length&1?"0"+e:e}function hs(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?zt:BigInt("0x"+s)}function yt(s){return hs(tt(s))}function ps(s){return hs(tt(ho(X(s)).reverse()))}function jt(s,e){ve(e),s=us(s);const r=gt(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function fs(s,e){return jt(s,e).reverse()}function ho(s){return Uint8Array.from(s)}const bt=s=>typeof s=="bigint"&&zt<=s;function po(s,e,r){return bt(s)&&bt(e)&&bt(r)&&e<=s&&s<r}function fo(s,e,r,t){if(!po(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function _o(s){let e;for(e=0;s>zt;s>>=Jt,e+=1);return e}const Yt=s=>(Jt<<BigInt(s))-Jt;function go(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=b=>new Uint8Array(b),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const h=()=>{c.fill(1),l.fill(0),u=0},_=(...b)=>r(l,ke(c,...b)),f=(b=n)=>{l=_(i,b),c=_(),b.length!==0&&(l=_(o,b),c=_())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let b=0;const A=[];for(;b<e;){c=_();const R=c.slice();A.push(R),b+=c.length}return ke(...A)};return(b,A)=>{h(),f(b);let R;for(;!(R=A(x()));)f();return h(),R}}function Xt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function _s(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),se=BigInt(1),Le=BigInt(2),gs=BigInt(3),xs=BigInt(4),ws=BigInt(5),xo=BigInt(7),ms=BigInt(8),wo=BigInt(9),ys=BigInt(16);function pe(s,e){const r=s%e;return r>=ae?r:e+r}function le(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function bs(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=pe(s,e),t=e,n=ae,i=se;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==se)throw new Error("invert: does not exist");return pe(n,e)}function Zt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Ss(s,e){const r=(s.ORDER+se)/xs,t=s.pow(e,r);return Zt(s,t,e),t}function mo(s,e){const r=(s.ORDER-ws)/ms,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return Zt(s,a,e),a}function yo(s){const e=St(s),r=vs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+xo)/ys;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const h=a.mul(l,n),_=a.mul(l,i),f=a.eql(a.sqr(u),c),x=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(_,h,x);const w=a.eql(a.sqr(u),c),b=a.cmov(l,u,w);return Zt(a,b,c),b}}function vs(s){if(s<gs)throw new Error("sqrt is not defined for small field");let e=s-se,r=0;for(;e%Le===ae;)e/=Le,r++;let t=Le;const n=St(s);for(;As(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Ss;let i=n.pow(t,e);const o=(e+se)/Le;return function(c,l){if(c.is0(l))return l;if(As(c,l)!==1)throw new Error("Cannot find square root");let u=r,h=c.mul(c.ONE,i),_=c.pow(l,e),f=c.pow(l,o);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let x=1,w=c.sqr(_);for(;!c.eql(w,c.ONE);)if(x++,w=c.sqr(w),x===u)throw new Error("Cannot find square root");const b=se<<BigInt(u-x-1),A=c.pow(h,b);u=x,h=c.sqr(A),_=c.mul(_,h),f=c.mul(f,A)}return f}}function bo(s){return s%xs===gs?Ss:s%ms===ws?mo:s%ys===wo?yo(s):vs(s)}const So=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vo(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=So.reduce((t,n)=>(t[n]="function",t),e);return Xt(s,r),s}function Eo(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===se)return e;let t=s.ONE,n=e;for(;r>ae;)r&se&&(t=s.mul(t,n)),n=s.sqr(n),r>>=se;return t}function Es(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function As(s,e){const r=(s.ORDER-se)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Ao(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Io{constructor(e,r={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ae);P(this,"ONE",se);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Ao(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return pe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}neg(e){return pe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return pe(e*e,this.ORDER)}add(e,r){return pe(e+r,this.ORDER)}sub(e,r){return pe(e-r,this.ORDER)}mul(e,r){return pe(e*r,this.ORDER)}pow(e,r){return Eo(this,e,r)}div(e,r){return pe(e*bs(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return bs(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=bo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?fs(e,this.BYTES):jt(e,this.BYTES)}fromBytes(e,r=!1){X(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?ps(e):yt(e);if(a&&(c=pe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Es(this,e)}cmov(e,r,t){return t?r:e}}function St(s,e={}){return new Io(s,e)}function Is(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Ts(s){const e=Is(s);return e+Math.ceil(e/2)}function To(s,e,r=!1){X(s);const t=s.length,n=Is(e),i=Ts(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?ps(s):yt(s),a=pe(o,e-se)+se;return r?fs(a,n):jt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ye=BigInt(0),De=BigInt(1);function vt(s,e){const r=e.negate();return s?r:e}function Rs(s,e){const r=Es(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function ks(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Qt(s,e){ks(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Yt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function Cs(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,h=a===0,_=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:_,isNegF:f,offsetF:l}}const er=new WeakMap,Ns=new WeakMap;function tr(s){return Ns.get(s)||1}function Os(s){if(s!==Ye)throw new Error("invalid wNAF")}class Ro{constructor(e,r){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ye;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Qt(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Qt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:_,offsetF:f}=Cs(t,a,o);t=c,u?i=i.add(vt(_,r[f])):n=n.add(vt(h,r[l]))}return Os(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Qt(e,this.bits);for(let o=0;o<i.windows&&t!==Ye;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Cs(t,o,i);if(t=a,!l){const h=r[c];n=n.add(u?h.negate():h)}}return Os(t),n}getPrecomputes(e,r,t){let n=er.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),er.set(r,n))),n}cached(e,r,t){const n=tr(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=tr(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){ks(r,this.bits),Ns.set(e,r),er.delete(e)}hasCache(e){return tr(e)!==1}}function ko(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ye||t>Ye;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function Ps(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vo(e),e}else return St(s,{isLE:r})}function Co(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ye))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Ps(e.p,r.Fp,t),i=Ps(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function No(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Ls{constructor(e,r){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(ss(e),X(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),je(n)}update(e){return Je(this),this.iHash.update(e),this}digestInto(e){Je(this),X(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ds=(s,e,r)=>new Ls(s,e).update(r).digest();Ds.create=(s,e)=>new Ls(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Bs=(s,e)=>(s+(s>=0?e:-e)/Ms)/e;function Oo(s,e,r){const[[t,n],[i,o]]=e,a=Bs(o*s,r),c=Bs(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const h=l<Ae,_=u<Ae;h&&(l=-l),_&&(u=-u);const f=Yt(Math.ceil(_o(r)/2))+Xe;if(l<Ae||l>=f||u<Ae||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:l,k2neg:_,k2:u}}function rr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function sr(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return wt(r.lowS,"lowS"),wt(r.prehash,"prehash"),r.format!==void 0&&rr(r.format),r}class Po extends Error{constructor(e=""){super(e)}}const Oe={Err:Po,_tlv:{encode:(s,e)=>{const{Err:r}=Oe;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=mt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?mt(n.length/2|128):"";return mt(s)+i+n+e},decode(s,e){const{Err:r}=Oe;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=Oe;if(s<Ae)throw new e("integer: negative integers are not allowed");let r=mt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Oe;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return yt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Oe,n=X(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Oe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Xe=BigInt(1),Ms=BigInt(2),Et=BigInt(3),Lo=BigInt(4);function Do(s,e={}){const r=Co("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Xt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Fs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(W,m,y){const{x:T,y:N}=m.toAffine(),$=t.toBytes(T);if(wt(y,"isCompressed"),y){u();const B=!t.isOdd(N);return ke($s(B),$)}else return ke(Uint8Array.of(4),$,t.toBytes(N))}function _(W){X(W,void 0,"Point");const{publicKey:m,publicKeyUncompressed:y}=l,T=W.length,N=W[0],$=W.subarray(1);if(T===m&&(N===2||N===3)){const B=t.fromBytes($);if(!t.isValid(B))throw new Error("bad point: is not on curve, wrong x");const M=w(B);let O;try{O=t.sqrt(M)}catch(E){const k=E instanceof Error?": "+E.message:"";throw new Error("bad point: is not on curve, sqrt error"+k)}u();const G=t.isOdd(O);return(N&1)===1!==G&&(O=t.neg(O)),{x:B,y:O}}else if(T===y&&N===4){const B=t.BYTES,M=t.fromBytes($.subarray(0,B)),O=t.fromBytes($.subarray(B,B*2));if(!b(M,O))throw new Error("bad point: is not on curve");return{x:M,y:O}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${y}`)}const f=e.toBytes||h,x=e.fromBytes||_;function w(W){const m=t.sqr(W),y=t.mul(m,W);return t.add(t.add(y,t.mul(W,i.a)),i.b)}function b(W,m){const y=t.sqr(m),T=w(W);return t.eql(y,T)}if(!b(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,Et),Lo),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,R)))throw new Error("bad curve params: a or b");function C(W,m,y=!1){if(!t.isValid(m)||y&&t.is0(m))throw new Error(`bad point coordinate ${W}`);return m}function D(W){if(!(W instanceof V))throw new Error("Weierstrass Point expected")}function H(W){if(!c||!c.basises)throw new Error("no endo");return Oo(W,c.basises,n.ORDER)}const K=_s((W,m)=>{const{X:y,Y:T,Z:N}=W;if(t.eql(N,t.ONE))return{x:y,y:T};const $=W.is0();m==null&&(m=$?t.ONE:t.inv(N));const B=t.mul(y,m),M=t.mul(T,m),O=t.mul(N,m);if($)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),re=_s(W=>{if(W.is0()){if(e.allowInfinityPoint&&!t.is0(W.Y))return;throw new Error("bad point: ZERO")}const{x:m,y}=W.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not field elements");if(!b(m,y))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function ie(W,m,y,T,N){return y=new V(t.mul(y.X,W),y.Y,y.Z),m=vt(T,m),y=vt(N,y),m.add(y)}const F=class F{constructor(m,y,T){P(this,"X");P(this,"Y");P(this,"Z");this.X=C("x",m),this.Y=C("y",y,!0),this.Z=C("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:y,y:T}=m||{};if(!m||!t.isValid(y)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof F)throw new Error("projective point not allowed");return t.is0(y)&&t.is0(T)?F.ZERO:new F(y,T,t.ONE)}static fromBytes(m){const y=F.fromAffine(x(X(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return F.fromBytes(gt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return L.createCache(this,m),y||this.multiply(Et),this}assertValidity(){re(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){D(m);const{X:y,Y:T,Z:N}=this,{X:$,Y:B,Z:M}=m,O=t.eql(t.mul(y,M),t.mul($,N)),G=t.eql(t.mul(T,M),t.mul(B,N));return O&&G}negate(){return new F(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:y}=i,T=t.mul(y,Et),{X:N,Y:$,Z:B}=this;let M=t.ZERO,O=t.ZERO,G=t.ZERO,S=t.mul(N,N),E=t.mul($,$),k=t.mul(B,B),I=t.mul(N,$);return I=t.add(I,I),G=t.mul(N,B),G=t.add(G,G),M=t.mul(m,G),O=t.mul(T,k),O=t.add(M,O),M=t.sub(E,O),O=t.add(E,O),O=t.mul(M,O),M=t.mul(I,M),G=t.mul(T,G),k=t.mul(m,k),I=t.sub(S,k),I=t.mul(m,I),I=t.add(I,G),G=t.add(S,S),S=t.add(G,S),S=t.add(S,k),S=t.mul(S,I),O=t.add(O,S),k=t.mul($,B),k=t.add(k,k),S=t.mul(k,I),M=t.sub(M,S),G=t.mul(k,E),G=t.add(G,G),G=t.add(G,G),new F(M,O,G)}add(m){D(m);const{X:y,Y:T,Z:N}=this,{X:$,Y:B,Z:M}=m;let O=t.ZERO,G=t.ZERO,S=t.ZERO;const E=i.a,k=t.mul(i.b,Et);let I=t.mul(y,$),U=t.mul(T,B),q=t.mul(N,M),J=t.add(y,T),z=t.add($,B);J=t.mul(J,z),z=t.add(I,U),J=t.sub(J,z),z=t.add(y,N);let Y=t.add($,M);return z=t.mul(z,Y),Y=t.add(I,q),z=t.sub(z,Y),Y=t.add(T,N),O=t.add(B,M),Y=t.mul(Y,O),O=t.add(U,q),Y=t.sub(Y,O),S=t.mul(E,z),O=t.mul(k,q),S=t.add(O,S),O=t.sub(U,S),S=t.add(U,S),G=t.mul(O,S),U=t.add(I,I),U=t.add(U,I),q=t.mul(E,q),z=t.mul(k,z),U=t.add(U,q),q=t.sub(I,q),q=t.mul(E,q),z=t.add(z,q),I=t.mul(U,z),G=t.add(G,I),I=t.mul(Y,z),O=t.mul(J,O),O=t.sub(O,I),I=t.mul(J,U),S=t.mul(Y,S),S=t.add(S,I),new F(O,G,S)}subtract(m){return this.add(m.negate())}is0(){return this.equals(F.ZERO)}multiply(m){const{endo:y}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,N;const $=B=>L.cached(this,B,M=>Rs(F,M));if(y){const{k1neg:B,k1:M,k2neg:O,k2:G}=H(m),{p:S,f:E}=$(M),{p:k,f:I}=$(G);N=E.add(I),T=ie(y.beta,S,k,B,O)}else{const{p:B,f:M}=$(m);T=B,N=M}return Rs(F,[T,N])[0]}multiplyUnsafe(m){const{endo:y}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ae||T.is0())return F.ZERO;if(m===Xe)return T;if(L.hasCache(this))return this.multiply(m);if(y){const{k1neg:N,k1:$,k2neg:B,k2:M}=H(m),{p1:O,p2:G}=ko(F,T,$,M);return ie(y.beta,O,G,N,B)}else return L.unsafe(T,m)}toAffine(m){return K(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Xe?!0:m?m(F,this):L.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Xe?this:m?m(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return wt(m,"isCompressed"),this.assertValidity(),f(F,this,m)}toHex(m=!0){return tt(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(F,"BASE",new F(i.Gx,i.Gy,t.ONE)),P(F,"ZERO",new F(t.ZERO,t.ONE,t.ZERO)),P(F,"Fp",t),P(F,"Fn",n);let V=F;const oe=n.BITS,L=new Ro(V,e.endo?Math.ceil(oe/2):oe);return V.BASE.precompute(8),V}function $s(s){return Uint8Array.of(s?2:3)}function Fs(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Bo(s,e={}){const{Fn:r}=s,t=e.randomBytes||ls,n=Object.assign(Fs(s.Fp,r),{seed:Ts(r.ORDER)});function i(f){try{const x=r.fromBytes(f);return r.isValidNot0(x)}catch{return!1}}function o(f,x){const{publicKey:w,publicKeyUncompressed:b}=n;try{const A=f.length;return x===!0&&A!==w||x===!1&&A!==b?!1:!!s.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return To(X(f,n.seed,"seed"),r.ORDER)}function c(f,x=!0){return s.BASE.multiply(r.fromBytes(f)).toBytes(x)}function l(f){const{secretKey:x,publicKey:w,publicKeyUncompressed:b}=n;if(!qt(f)||"_lengths"in r&&r._lengths||x===w)return;const A=X(f,void 0,"key").length;return A===w||A===b}function u(f,x,w=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const b=r.fromBytes(f);return s.fromBytes(x).multiply(b).toBytes(w)}const h={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=No(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:s,utils:h,lengths:n})}function Mo(s,e,r={}){ss(e),Xt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||ls,n=r.hmac||((m,y)=>Ds(e,m,y)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:f}=Bo(s,r),x={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*Ms<i.ORDER;function b(m){const y=a>>Xe;return m>y}function A(m,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function R(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function C(m,y){rr(y);const T=f.signature,N=y==="compact"?T:y==="recovered"?T+1:void 0;return X(m,N)}class D{constructor(y,T,N){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=A("r",y),this.s=A("s",T),N!=null){if(R(),![0,1,2,3].includes(N))throw new Error("invalid recovery id");this.recovery=N}Object.freeze(this)}static fromBytes(y,T=x.format){C(y,T);let N;if(T==="der"){const{r:O,s:G}=Oe.toSig(X(y));return new D(O,G)}T==="recovered"&&(N=y[0],T="compact",y=y.subarray(1));const $=f.signature/2,B=y.subarray(0,$),M=y.subarray($,$*2);return new D(o.fromBytes(B),o.fromBytes(M),N)}static fromHex(y,T){return this.fromBytes(gt(y),T)}assertRecovery(){const{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new D(this.r,this.s,y)}recoverPublicKey(y){const{r:T,s:N}=this,$=this.assertRecovery(),B=$===2||$===3?T+a:T;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes(B),O=s.fromBytes(ke($s(($&1)===0),M)),G=o.inv(B),S=K(X(y,void 0,"msgHash")),E=o.create(-S*G),k=o.create(N*G),I=s.BASE.multiplyUnsafe(E).add(O.multiplyUnsafe(k));if(I.is0())throw new Error("invalid recovery: point at infinify");return I.assertValidity(),I}hasHighS(){return b(this.s)}toBytes(y=x.format){if(rr(y),y==="der")return gt(Oe.hexFromSig(this));const{r:T,s:N}=this,$=o.toBytes(T),B=o.toBytes(N);return y==="recovered"?(R(),ke(Uint8Array.of(this.assertRecovery()),$,B)):ke($,B)}toHex(y){return tt(this.toBytes(y))}}const H=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const T=yt(y),N=y.length*8-c;return N>0?T>>BigInt(N):T},K=r.bits2int_modN||function(y){return o.create(H(y))},re=Yt(c);function ie(m){return fo("num < 2^"+c,m,Ae,re),o.toBytes(m)}function V(m,y){return X(m,void 0,"message"),y?X(e(m),void 0,"prehashed message"):m}function oe(m,y,T){const{lowS:N,prehash:$,extraEntropy:B}=sr(T,x);m=V(m,$);const M=K(m),O=o.fromBytes(y);if(!o.isValidNot0(O))throw new Error("invalid private key");const G=[ie(O),ie(M)];if(B!=null&&B!==!1){const I=B===!0?t(f.secretKey):B;G.push(X(I,void 0,"extraEntropy"))}const S=ke(...G),E=M;function k(I){const U=H(I);if(!o.isValidNot0(U))return;const q=o.inv(U),J=s.BASE.multiply(U).toAffine(),z=o.create(J.x);if(z===Ae)return;const Y=o.create(q*o.create(E+z*O));if(Y===Ae)return;let We=(J.x===z?0:2)|Number(J.y&Xe),fn=Y;return N&&b(Y)&&(fn=o.neg(Y),We^=1),new D(z,fn,w?void 0:We)}return{seed:S,k2sig:k}}function L(m,y,T={}){const{seed:N,k2sig:$}=oe(m,y,T);return go(e.outputLen,o.BYTES,n)(N,$).toBytes(T.format)}function F(m,y,T,N={}){const{lowS:$,prehash:B,format:M}=sr(N,x);if(T=X(T,void 0,"publicKey"),y=V(y,B),!qt(m)){const O=m instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}C(m,M);try{const O=D.fromBytes(m,M),G=s.fromBytes(T);if($&&O.hasHighS())return!1;const{r:S,s:E}=O,k=K(y),I=o.inv(E),U=o.create(k*I),q=o.create(S*I),J=s.BASE.multiplyUnsafe(U).add(G.multiplyUnsafe(q));return J.is0()?!1:o.create(J.x)===S}catch{return!1}}function W(m,y,T={}){const{prehash:N}=sr(T,x);return y=V(y,N),D.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:f,Point:s,sign:L,verify:F,recoverPublicKey:W,Signature:D,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},$o={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ws=BigInt(2);function Fo(s){const e=nr.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,h=le(u,r,e)*u%e,_=le(h,r,e)*u%e,f=le(_,Ws,e)*l%e,x=le(f,n,e)*f%e,w=le(x,i,e)*x%e,b=le(w,a,e)*w%e,A=le(b,c,e)*b%e,R=le(A,a,e)*w%e,C=le(R,r,e)*u%e,D=le(C,o,e)*x%e,H=le(D,t,e)*l%e,K=le(H,Ws,e);if(!ir.eql(ir.sqr(K),s))throw new Error("Cannot find square root");return K}const ir=St(nr.p,{sqrt:Fo}),Wo=Mo(Do(nr,{Fp:ir,endo:$o}),uo),Uo=BigInt(0),rt=BigInt(1),Ho=BigInt(2),Go=BigInt(7),Ko=BigInt(256),qo=BigInt(113),Us=[],Hs=[],Gs=[];for(let s=0,e=rt,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],Us.push(2*(5*t+r)),Hs.push((s+1)*(s+2)/2%64);let n=Uo;for(let i=0;i<7;i++)e=(e<<rt^(e>>Go)*qo)%Ko,e&Ho&&(n^=rt<<(rt<<BigInt(i))-rt);Gs.push(n)}const Ks=ro(Gs,!0),Vo=Ks[0],zo=Ks[1],qs=(s,e,r)=>r>32?io(s,e,r):so(s,e,r),Vs=(s,e,r)=>r>32?oo(s,e,r):no(s,e,r);function Jo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=qs(l,u,1)^r[a],_=Vs(l,u,1)^r[a+1];for(let f=0;f<50;f+=10)s[o+f]^=h,s[o+f+1]^=_}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=Hs[o],c=qs(n,i,a),l=Vs(n,i,a),u=Us[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Vo[t],s[1]^=zo[t]}je(r)}class or{constructor(e,r,t,n=!1,i=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Vi(this.state)}clone(){return this._cloneInto()}keccak(){is(this.state32),Jo(this.state32,this.rounds),is(this.state32),this.posOut=0,this.pos=0}update(e){Je(this),X(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Je(this,!1),X(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ns(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,je(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new or(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const zs=((s,e,r,t={})=>cs(()=>new or(e,s,r),t))(1,136,32),jo=60;class Yo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Gi(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+jo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Li(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return qi(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
7
+ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=zs(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Xo(a),l=c.slice(0,32),u=c.slice(32,64),h=c[64],_=h>=27?h-27:h,w=new Wo.Signature(Js(l),Js(u)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),b=zs(w);return"0x"+tt(b.slice(12))}}function Xo(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Js(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Zo=3e4,Qo=1e3;class ea{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,Qo*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Zo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const ta=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i];function ar(){return typeof window>"u"?void 0:window}function ra(){const s=ar();return s==null?void 0:s.__crossx}function sa(s){return s==="ios"||s==="android"?s:null}function cr(){const s=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(s)?"android":/iPhone|iPad|iPod|Macintosh/i.test(s)?"ios":null}function na(s,e){const r=o=>o.split(/[^\d]+/).filter(a=>a!=="").map(a=>Number.parseInt(a,10)),t=r(s),n=r(e),i=Math.max(t.length,n.length);for(let o=0;o<i;o+=1){const a=(t[o]??0)-(n[o]??0);if(a!==0)return a}return 0}function ia(){const s=ar();if(!s)return!1;const e=s.__crossxRNBridge;return e!=null&&e.isInstalled?!0:s.__CROSSX_BRIDGE_INITIALIZED__===!0||s.__CROSSX_RN_BRIDGE_READY__===!0}function js(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of ta){const r=e.exec(s);if(r)return r[1]??null}}function st(){const s=ra();if(s!=null&&s.browser)return{version:s.version??null,platform:sa(s.platform)??cr(),detectedBy:"marker"};if(ia())return{version:js()??null,platform:cr(),detectedBy:"bridge"};const e=js();return e!==void 0?{version:e,platform:cr(),detectedBy:"user-agent"}:null}function oa(){return st()!==null}function aa(s=3e3){const e=st();return e?Promise.resolve(e):ar()?new Promise(r=>{const t=Date.now(),n=setInterval(()=>{const i=st();if(i){clearInterval(n),r(i);return}Date.now()-t>=s&&(clearInterval(n),r(null))},50)}):Promise.resolve(null)}const ca=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io","https://one-wallet-oauth.onechain.nexus","https://stg-one-wallet-oauth.onechain.nexus","https://dev-one-wallet-oauth.onechain.nexus"]),la="crossx://oauth-callback",da="2.3.2";function ua(s){return s.platform!=="ios"?!1:s.version?na(s.version,da)<=0:!0}class Be{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(d.log("[CROSSx] OAuth 대기 중단 —",e),r(e))}static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Be.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Be.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Be.generateRandom16Hex(),l=Be.generateRandom16Hex(),u=st();let h=e.authUrl;u&&e.legacyAuthUrl&&ua(u)&&(h=e.legacyAuthUrl,d.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:u.version??"(unknown)",detectedBy:u.detectedBy,authUrlBase:e.legacyAuthUrl}));const _=h.includes("?")?"&":"?",f=encodeURIComponent(window.location.origin);let x=`${h}${_}state=${c}&nonce=${l}&origin=${f}`;u&&!x.includes("redirectUrl=")&&(x+=`&redirectUrl=${encodeURIComponent(la)}`,d.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:u.detectedBy,appVersion:u.version??"(unknown)",platform:u.platform??"(unknown)"})),d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:h});const w=window.open(x,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!w){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const b=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),re(),t(new Error("Authentication timeout"))},5*60*1e3),A=10,R=30;let C=0,D=null;const H=()=>{clearInterval(K),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+R+"초간 대기합니다"),D=setTimeout(()=>{re(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},R*1e3)},K=setInterval(()=>{C++;try{if(!w.closed)return;const V=typeof document<"u"&&document.hasFocus();C<=A&&!V?H():(re(),t(new Error("로그인이 취소되었습니다")))}catch{H()}},1e3),re=()=>{this.abortPending=null,clearTimeout(b),clearInterval(K),D&&clearTimeout(D),window.removeEventListener("message",ie)},ie=V=>{if(!ca.has(V.origin))return;re();const oe=typeof V.data.status=="string",L=oe?V.data.data??{}:V.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:oe?"wrapped":"flat",status:oe?V.data.status:"(flat)"});const F=(L==null?void 0:L.state)??V.data.state;if(!F||F!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(oe&&V.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",L==null?void 0:L.error),t(new Error((L==null?void 0:L.error)||"Authentication failed"));return}if(!oe&&(L!=null&&L.error)){d.error("[CROSSx] OAuth 실패:",L.error),t(new Error(L.error||"Authentication failed"));return}const W=L==null?void 0:L.idToken,m=L==null?void 0:L.accessToken,y=m??W,T=(L==null?void 0:L.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!m,hasIdToken:!!W,hasEmail:!!T}),!y){d.error("[CROSSx] 토큰을 찾을 수 없음:",V.data),t(new Error("Token not found in response"));return}const N={token:y,email:T},$=B=>{Be.verifyIdTokenNonce(B,l).then(()=>r(N)).catch(M=>{d.error("[CROSSx] nonce 검증 실패:",M),t(M instanceof Error?M:new Error("nonce verification failed"))})};m?m.split(".").length===3?$(m):W?$(W):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(N)):W?$(W):t(new Error("Token not found in response"))};this.abortPending=V=>{re(),t(new Error(V))},window.addEventListener("message",ie)})}}const nt="crossx_wallet_data",Ze="crossx_mock_pin_hash";class ha{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(nt)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(nt);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(nt,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Ze,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(nt);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ze);return r&&r!==e?!1:(r||await this.storage.set(Ze,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(p.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ze);if(n&&t&&n!==t)throw new g(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ze,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new g(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new g(p.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(nt,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ze,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Me{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(vr))return e;const r=!e||this.tokenStore.isExpiringSoon(vr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,h;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const f=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(f&&typeof f.code=="number"){if(f.code<0||f.code>=400){const x=f.message||f.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:f.code,message:x,url:o,method:e});const w=Me.mapGatewayError(f.code,f.data);if(w===p.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(w===p.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(p.USER_NOT_FOUND,Me.getGatewayErrorMessage(f.code,x));const b=w===p.AUTH_NOT_AUTHENTICATED?p.SESSION_EXPIRED:w,A=b===p.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Me.getGatewayErrorMessage(f.code,x),R=f.data;let C;throw w===p.PIN_LOCKED?C=Me.extractLockDetails(R):w===p.ADDRESS_LIMIT_EXCEEDED?C={limit:ot,raw:R}:C=R??void 0,new g(b,A,C)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:f.code,url:o,method:e}),f.data??f}return f}catch(_){if(_ instanceof g)throw _;const f=((l=_.response)==null?void 0:l.status)??_.status;if((f===401||f===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${f} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const x=_.response.data,w=x.message||x.data||"API 요청에 실패했습니다",b=x.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:b,message:w,url:o,method:e,status:(h=_.response)==null?void 0:h.status}),new g(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${b}): ${w}`)}throw _}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new g(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new g(p.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 g(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new g(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new g(p.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new g(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10007:return p.BROADCAST_FAILED;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10004:return p.WALLET_ALREADY_EXISTS;case-10005:return p.WALLET_NOT_FOUND;case-10011:return p.WALLET_NOT_FOUND;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10013:return p.WITHDRAW_FAILED;case-10033:return p.USER_NOT_FOUND;case-10036:return p.ADDRESS_LIMIT_EXCEEDED;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10025:return p.INVALID_APP_TYPE;case-10028:return Me.hasLockInfo(r)?p.PIN_LOCKED:p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10032:return p.PIN_REPEATED_PATTERN;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10040:return p.HMAC_REQUIRED;case-10041:return p.HMAC_VERIFICATION_FAILED;default:return p.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 ${ot} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class pa{constructor(e,r,t,n=()=>{},i=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,this.getAppName=i,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(o,a)=>e.prepare(o,a)),e.migrateWallet&&(this.migrateWallet=(o,a)=>e.migrateWallet(o,a)),e.verifyPin&&(this.verifyPin=o=>e.verifyPin(o)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(o,a)=>e.verifyRecoveryPin(o,a))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();const c=await a.signMessage({chainId:r,message:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){this.assertBridgeSessionActive();const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return this.assertBridgeSessionActive(),{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,dappName:this.getAppName()})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class it{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=it.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?yn:mn;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 g(it.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=it.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new g(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(ct).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const Ys="__crossx-confirm-style",ee="__crossx-confirm-overlay",fa={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 Xs(s,e){const r=fa[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary,contentHigh:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const _a=`
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
- #${re} {
10
+ #${ee} {
11
11
  position: fixed;
12
12
  inset: 0;
13
13
  z-index: 2147483647;
@@ -1543,7 +1543,7 @@ button.__crossx-connect-other-block:active {
1543
1543
  }
1544
1544
  /* ── Mobile bottom sheet ───────────────────────────────────── */
1545
1545
  @media (max-width: 480px) {
1546
- #${re} {
1546
+ #${ee} {
1547
1547
  align-items: flex-end;
1548
1548
  /*
1549
1549
  * iOS Safari 는 soft keyboard 가 떠도 layout viewport 를 축소시키지 않아
@@ -1842,7 +1842,7 @@ button.__crossx-connect-other-block:active {
1842
1842
 
1843
1843
  /* ── Landscape for signing/transaction modals ──────────── */
1844
1844
  @media (orientation: landscape) and (max-height: 500px) {
1845
- #${re} { align-items: center !important; overflow: hidden; }
1845
+ #${ee} { align-items: center !important; overflow: hidden; }
1846
1846
  .__crossx-card--send-tx,
1847
1847
  .__crossx-card--sign-tx,
1848
1848
  .__crossx-card--sign-msg,
@@ -2604,31 +2604,31 @@ button.__crossx-connect-other-block:active {
2604
2604
  .__crossx-tip-overlay.--visible {
2605
2605
  display: block;
2606
2606
  }
2607
- `;function de(){let s=document.getElementById(js);s||(s=document.createElement("style"),s.id=js,document.head.appendChild(s)),s.textContent=ua}function ha(){const s=`#${re}`,e=t=>{var n,i;(i=(n=t.target)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()},r=t=>{var n,i;(i=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function ue(s){const e=s.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const c=a[1].trim();s.style.setProperty("--cx-bg",c);const l=document.createElement("div");l.className="__crossx-safe-area-fill",l.style.background=c,s.appendChild(l)}}const r=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(o,r);s.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])s.addEventListener(o,r);s.addEventListener("touchmove",o=>{o.stopPropagation();let a=o.target;for(;a&&a!==s;){const c=window.getComputedStyle(a);if((c.overflowY==="auto"||c.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}o.preventDefault()},{passive:!1});const t=ha(),n=pa(s),i=s.remove.bind(s);s.remove=()=>{n(),t(),i()},document.body.appendChild(s)}function pa(s){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const n=window.innerHeight,i=e.offsetTop+e.height,o=Math.max(0,Math.round(n-i));o!==r&&(r=o,s.style.setProperty("--cx-keyboard-inset",`${o}px`))};return t(),e.addEventListener("resize",t),e.addEventListener("scroll",t),()=>{e.removeEventListener("resize",t),e.removeEventListener("scroll",t),s.style.removeProperty("--cx-keyboard-inset")}}function fa(s){const e=Array.from(s.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",s.appendChild(r);let t=null;const n=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const c=o.getBoundingClientRect(),l=r.offsetWidth,u=r.offsetHeight;let h=c.right-l,_=c.top-u-6;h<8&&(h=8),_<8&&(_=c.bottom+6),r.style.left=`${h}px`,r.style.top=`${_}px`,t=o},i=()=>{r.classList.remove("--visible"),t=null};e.forEach(o=>{o.addEventListener("mouseenter",()=>n(o)),o.addEventListener("mouseleave",i),o.addEventListener("touchstart",a=>{a.stopPropagation(),t===o?i():n(o)},{passive:!0})}),s.addEventListener("touchstart",o=>{o.target.closest(".__crossx-amount-tip")||i()},{passive:!0})}const _a=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function $e(){if(_a()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function Ie(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function Xs(s){return s?s.length<=13?s:`${s.slice(0,6)}...${s.slice(-4)}`:"—"}function Zs(s,e="ONE",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=pr(n,r,t);if(i==="0")return null;const o=ur(n,r);return hr(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const Qs={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"},cr=new Map;let lr=!1;function ga(){if(lr||(lr=!0,typeof fetch>"u"))return;const s=Ot().contentsBaseUrl;s&&fetch(`${s}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,n]of Object.entries(r)){const i=Number(t);!Number.isNaN(i)&&n&&cr.set(i,n)}}).catch(()=>{lr=!1})}function en(s){return parseInt(s.split(":")[1]??"",10)}function tn(s){var r;const e=en(s);if(!isNaN(e)){const t=(r=cr.get(e))==null?void 0:r.name;if(t)return t;if(Qs[e])return Qs[e]}return s}function dr(s,e){var r;if(s){const t=en(s);if(!isNaN(t)){const n=(r=cr.get(t))==null?void 0:r.nativeSymbol;if(n)return n}}return e}function ur(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,i=(s%r).toString().padStart(e,"0").replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function hr(s,e){return s===e?v(s):`<span class="__crossx-amount-tip" data-full="${v(e)}">${v(s)}</span>`}function pr(s,e,r){if(s===0n)return"0";const t=10n**BigInt(e),n=s/t,a=(s%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${n}.${a}`:`${n}`}function fr(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function xa(s){try{return BigInt(s).toLocaleString()}catch{return s}}function wa(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeDecimals:o=18}=s,a=dr(s.chainId,s.nativeSymbol??"ETH");if(!r)return null;try{const c=BigInt(r),l=xa(r);if(n){const u=c*BigInt(n);return{isDynamic:!0,estTxFee:hr(`${pr(u,o,e)} ${a}`,`${ur(u,o)} ${a}`),maxFeeGwei:fr(n),maxPriorityFeeGwei:i?fr(i):void 0,gasLimitFormatted:l}}if(t){const u=c*BigInt(t);return{isDynamic:!1,estTxFee:hr(`${pr(u,o,e)} ${a}`,`${ur(u,o)} ${a}`),gasPriceGwei:fr(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function rn(s,e,r){const t=wa(s,e);if(!t)return ee((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=ee((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=ee((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=ee((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=ee((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=ee((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),n}const Te=`<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 de(){let s=document.getElementById(Ys);s||(s=document.createElement("style"),s.id=Ys,document.head.appendChild(s)),s.textContent=_a}function ga(){const s=`#${ee}`,e=t=>{var n,i;(i=(n=t.target)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()},r=t=>{var n,i;(i=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function ue(s){const e=s.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const c=a[1].trim();s.style.setProperty("--cx-bg",c);const l=document.createElement("div");l.className="__crossx-safe-area-fill",l.style.background=c,s.appendChild(l)}}const r=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(o,r);s.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])s.addEventListener(o,r);s.addEventListener("touchmove",o=>{o.stopPropagation();let a=o.target;for(;a&&a!==s;){const c=window.getComputedStyle(a);if((c.overflowY==="auto"||c.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}o.preventDefault()},{passive:!1});const t=ga(),n=xa(s),i=s.remove.bind(s);s.remove=()=>{n(),t(),i()},document.body.appendChild(s)}function xa(s){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const n=window.innerHeight,i=e.offsetTop+e.height,o=Math.max(0,Math.round(n-i));o!==r&&(r=o,s.style.setProperty("--cx-keyboard-inset",`${o}px`))};return t(),e.addEventListener("resize",t),e.addEventListener("scroll",t),()=>{e.removeEventListener("resize",t),e.removeEventListener("scroll",t),s.style.removeProperty("--cx-keyboard-inset")}}function wa(s){const e=Array.from(s.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",s.appendChild(r);let t=null;const n=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const c=o.getBoundingClientRect(),l=r.offsetWidth,u=r.offsetHeight;let h=c.right-l,_=c.top-u-6;h<8&&(h=8),_<8&&(_=c.bottom+6),r.style.left=`${h}px`,r.style.top=`${_}px`,t=o},i=()=>{r.classList.remove("--visible"),t=null};e.forEach(o=>{o.addEventListener("mouseenter",()=>n(o)),o.addEventListener("mouseleave",i),o.addEventListener("touchstart",a=>{a.stopPropagation(),t===o?i():n(o)},{passive:!0})}),s.addEventListener("touchstart",o=>{o.target.closest(".__crossx-amount-tip")||i()},{passive:!0})}const ma=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function $e(){if(ma()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function Ie(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function Zs(s){return s?s.length<=13?s:`${s.slice(0,6)}...${s.slice(-4)}`:"—"}function Qs(s,e="ONE",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=fr(n,r,t);if(i==="0")return null;const o=hr(n,r);return pr(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const en={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"},lr=new Map;let dr=!1;function ya(){if(dr||(dr=!0,typeof fetch>"u"))return;const s=Pt().contentsBaseUrl;s&&fetch(`${s}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,n]of Object.entries(r)){const i=Number(t);!Number.isNaN(i)&&n&&lr.set(i,n)}}).catch(()=>{dr=!1})}function tn(s){return parseInt(s.split(":")[1]??"",10)}function rn(s){var r;const e=tn(s);if(!isNaN(e)){const t=(r=lr.get(e))==null?void 0:r.name;if(t)return t;if(en[e])return en[e]}return s}function ur(s,e){var r;if(s){const t=tn(s);if(!isNaN(t)){const n=(r=lr.get(t))==null?void 0:r.nativeSymbol;if(n)return n}}return e}function hr(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,i=(s%r).toString().padStart(e,"0").replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function pr(s,e){return s===e?v(s):`<span class="__crossx-amount-tip" data-full="${v(e)}">${v(s)}</span>`}function fr(s,e,r){if(s===0n)return"0";const t=10n**BigInt(e),n=s/t,a=(s%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${n}.${a}`:`${n}`}function _r(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function ba(s){try{return BigInt(s).toLocaleString()}catch{return s}}function Sa(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeDecimals:o=18}=s,a=ur(s.chainId,s.nativeSymbol??"ETH");if(!r)return null;try{const c=BigInt(r),l=ba(r);if(n){const u=c*BigInt(n);return{isDynamic:!0,estTxFee:pr(`${fr(u,o,e)} ${a}`,`${hr(u,o)} ${a}`),maxFeeGwei:_r(n),maxPriorityFeeGwei:i?_r(i):void 0,gasLimitFormatted:l}}if(t){const u=c*BigInt(t);return{isDynamic:!1,estTxFee:pr(`${fr(u,o,e)} ${a}`,`${hr(u,o)} ${a}`),gasPriceGwei:_r(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function sn(s,e,r){const t=Sa(s,e);if(!t)return Z((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=Z((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=Z((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=Z((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=Z((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=Z((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),n}const Te=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2608
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
- </svg>`,ie=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2610
+ </svg>`,ne=`<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>`,ma=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2613
+ </svg>`,va=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2614
2614
  <circle cx="20" cy="20" r="20" fill="#00D5AA"/>
2615
2615
  <path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/>
2616
- </svg>`,ya='<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>',ba='<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>',Sa='<svg width="16" height="16" viewBox="0 0 229 229" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><g clip-path="url(#clip0_74746_12130)"><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_74746_12130)"><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_74746_12130)"/></g><path d="M79.7598 228.096H228.24V64.7367L79.7598 159.851V228.096Z" fill="url(#paint1_linear_74746_12130)"/><path d="M79.7694 228.209H0.0332031V75.9257L79.7694 160.218V228.209Z" fill="url(#paint2_linear_74746_12130)"/><g filter="url(#filter1_d_74746_12130)"><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_74746_12130" 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_74746_12130"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_74746_12130" result="shape"/></filter><filter id="filter1_d_74746_12130" 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_74746_12130"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_74746_12130" result="shape"/></filter><linearGradient id="paint0_linear_74746_12130" 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_74746_12130" 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_74746_12130" 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_74746_12130"><rect width="228.273" height="228.273" rx="87" fill="white"/></clipPath></defs></svg>',va={[Ue.MetaMask]:ya,[Ue.Binance]:ba,[Ue.CROSSx]:Sa},sn='<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"/>',_r=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${sn}</svg>`,Ea=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2616
+ </svg>`,Ea='<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>',Aa='<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>',Ia='<svg width="16" height="16" viewBox="0 0 229 229" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><g clip-path="url(#clip0_74746_12130)"><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_74746_12130)"><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_74746_12130)"/></g><path d="M79.7598 228.096H228.24V64.7367L79.7598 159.851V228.096Z" fill="url(#paint1_linear_74746_12130)"/><path d="M79.7694 228.209H0.0332031V75.9257L79.7694 160.218V228.209Z" fill="url(#paint2_linear_74746_12130)"/><g filter="url(#filter1_d_74746_12130)"><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_74746_12130" 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_74746_12130"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_74746_12130" result="shape"/></filter><filter id="filter1_d_74746_12130" 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_74746_12130"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_74746_12130" result="shape"/></filter><linearGradient id="paint0_linear_74746_12130" 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_74746_12130" 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_74746_12130" 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_74746_12130"><rect width="228.273" height="228.273" rx="87" fill="white"/></clipPath></defs></svg>',Ta={[Ue.MetaMask]:Ea,[Ue.Binance]:Aa,[Ue.CROSSx]:Ia},nn='<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"/>',gr=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${nn}</svg>`,Ra=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2617
2617
  <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)"/>
2618
- </svg>`,Aa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2618
+ </svg>`,ka=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2619
2619
  <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
2620
2620
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
2621
2621
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
2622
- </svg>`;function ce(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-border-medium:${s.borderMedium}`,`--cx-title:${s.titleColor}`,`--cx-content-high:${s.contentHigh}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-surface-high:${s.surfaceHigh}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-primary-gradient:${s.primaryGradient}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-notice-bg:${s.noticeBg}`,`--cx-notice-border:${s.noticeBorder}`,`--cx-notice-title:${s.noticeTitleColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function Ia(s,e){s.style.setProperty("--cx-bg",e.bg),s.style.setProperty("--cx-border",e.border),s.style.setProperty("--cx-border-medium",e.borderMedium),s.style.setProperty("--cx-title",e.titleColor),s.style.setProperty("--cx-subtitle",e.subtitleColor),s.style.setProperty("--cx-label",e.labelColor),s.style.setProperty("--cx-value",e.valueColor),s.style.setProperty("--cx-pill-bg",e.pillBg),s.style.setProperty("--cx-pill-from",e.pillFromColor),s.style.setProperty("--cx-pill-amt",e.pillAmtColor),s.style.setProperty("--cx-divider",e.divider),s.style.setProperty("--cx-close",e.closeColor),s.style.setProperty("--cx-close-hover",e.closeHoverBg),s.style.setProperty("--cx-copy",e.copyColor),s.style.setProperty("--cx-input-bg",e.inputBg),s.style.setProperty("--cx-input-border",e.inputBorder),s.style.setProperty("--cx-hint",e.hintColor),s.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),s.style.setProperty("--cx-surface-high",e.surfaceHigh),s.style.setProperty("--cx-primary",e.primary),s.style.setProperty("--cx-primary-glow",e.primaryGlow),s.style.setProperty("--cx-primary-gradient",e.primaryGradient),s.style.setProperty("--cx-secondary",e.secondary),s.style.setProperty("--cx-error",e.errorColor),s.style.setProperty("--cx-notice-bg",e.noticeBg),s.style.setProperty("--cx-notice-border",e.noticeBorder),s.style.setProperty("--cx-notice-title",e.noticeTitleColor),s.style.setProperty("--cx-on-primary",e.onPrimary)}function ee(s,e){return`
2622
+ </svg>`;function ce(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-border-medium:${s.borderMedium}`,`--cx-title:${s.titleColor}`,`--cx-content-high:${s.contentHigh}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-surface-high:${s.surfaceHigh}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-primary-gradient:${s.primaryGradient}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-notice-bg:${s.noticeBg}`,`--cx-notice-border:${s.noticeBorder}`,`--cx-notice-title:${s.noticeTitleColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function Ca(s,e){s.style.setProperty("--cx-bg",e.bg),s.style.setProperty("--cx-border",e.border),s.style.setProperty("--cx-border-medium",e.borderMedium),s.style.setProperty("--cx-title",e.titleColor),s.style.setProperty("--cx-subtitle",e.subtitleColor),s.style.setProperty("--cx-label",e.labelColor),s.style.setProperty("--cx-value",e.valueColor),s.style.setProperty("--cx-pill-bg",e.pillBg),s.style.setProperty("--cx-pill-from",e.pillFromColor),s.style.setProperty("--cx-pill-amt",e.pillAmtColor),s.style.setProperty("--cx-divider",e.divider),s.style.setProperty("--cx-close",e.closeColor),s.style.setProperty("--cx-close-hover",e.closeHoverBg),s.style.setProperty("--cx-copy",e.copyColor),s.style.setProperty("--cx-input-bg",e.inputBg),s.style.setProperty("--cx-input-border",e.inputBorder),s.style.setProperty("--cx-hint",e.hintColor),s.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),s.style.setProperty("--cx-surface-high",e.surfaceHigh),s.style.setProperty("--cx-primary",e.primary),s.style.setProperty("--cx-primary-glow",e.primaryGlow),s.style.setProperty("--cx-primary-gradient",e.primaryGradient),s.style.setProperty("--cx-secondary",e.secondary),s.style.setProperty("--cx-error",e.errorColor),s.style.setProperty("--cx-notice-bg",e.noticeBg),s.style.setProperty("--cx-notice-border",e.noticeBorder),s.style.setProperty("--cx-notice-title",e.noticeTitleColor),s.style.setProperty("--cx-on-primary",e.onPrimary)}function Z(s,e){return`
2623
2623
  <div class="__crossx-row">
2624
2624
  <span class="__crossx-row-label">${s}</span>
2625
2625
  <div class="__crossx-row-value">${e}</div>
2626
- </div>`}function Ta(s,e,r,t){const n=e,i=dr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=At(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ie(s.to)}</span>
2627
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=rn(s,r,t),u=Zs(s.value,i,o,r),h=u?ee((t==null?void 0:t.label_value)??"Value",`<span>${u}</span>`):"",_=s.data??"0x",f=document.createElement("div");return f.id=re,f.innerHTML=`
2626
+ </div>`}function Na(s,e,r,t){const n=e,i=ur(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=At(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ie(s.to)}</span>
2627
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=sn(s,r,t),u=Qs(s.value,i,o,r),h=u?Z((t==null?void 0:t.label_value)??"Value",`<span>${u}</span>`):"",_=s.data??"0x",f=document.createElement("div");return f.id=ee,f.innerHTML=`
2628
2628
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ce(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2629
2629
  <div class="__crossx-header">
2630
2630
  <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
2631
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2631
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2632
2632
  </div>
2633
2633
  <hr class="__crossx-divider">
2634
2634
  <div class="__crossx-body">
@@ -2638,7 +2638,7 @@ button.__crossx-connect-other-block:active {
2638
2638
  <span class="__crossx-sig-origin">${v(a)}</span>${v((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
2639
2639
  </p>
2640
2640
  <div class="__crossx-addr-pill">
2641
- ${_r}
2641
+ ${gr}
2642
2642
  <span class="__crossx-addr-pill-text">${Ie(s.from)}</span>
2643
2643
  </div>
2644
2644
  <p class="__crossx-warning">${v((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
@@ -2646,8 +2646,8 @@ button.__crossx-connect-other-block:active {
2646
2646
  <hr class="__crossx-divider __crossx-divider--cols">
2647
2647
  <div class="__crossx-col-right-sign">
2648
2648
  <div class="__crossx-rows">
2649
- ${ee((t==null?void 0:t.label_to)??"To",c)}
2650
- ${ee((t==null?void 0:t.label_network)??"Network",`<span>${tn(s.chainId)}</span>`)}
2649
+ ${Z((t==null?void 0:t.label_to)??"To",c)}
2650
+ ${Z((t==null?void 0:t.label_network)??"Network",`<span>${rn(s.chainId)}</span>`)}
2651
2651
  ${h}
2652
2652
  ${l}
2653
2653
  </div>
@@ -2660,12 +2660,12 @@ button.__crossx-connect-other-block:active {
2660
2660
  </div>
2661
2661
  </div>
2662
2662
  </div>
2663
- `,f}const Ra=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function ka(s){return s?Ra.has(s.slice(0,10).toLowerCase()):!1}function Ca(s,e,r,t){const n=e,i=dr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=At(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ie(s.to)}</span>
2664
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=rn(s,r,t),h=Zs(s.value,i,o,r)??"—",_=ka(s.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",f=document.createElement("div");return f.id=re,f.innerHTML=`
2663
+ `,f}const Oa=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Pa(s){return s?Oa.has(s.slice(0,10).toLowerCase()):!1}function La(s,e,r,t){const n=e,i=ur(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=At(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ie(s.to)}</span>
2664
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=sn(s,r,t),h=Qs(s.value,i,o,r)??"—",_=Pa(s.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",f=document.createElement("div");return f.id=ee,f.innerHTML=`
2665
2665
  <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ce(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2666
2666
  <div class="__crossx-header">
2667
2667
  <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
2668
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2668
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2669
2669
  </div>
2670
2670
  <hr class="__crossx-divider">
2671
2671
  <div class="__crossx-body">
@@ -2674,8 +2674,8 @@ button.__crossx-connect-other-block:active {
2674
2674
  </p>
2675
2675
  <div class="__crossx-body-cols">
2676
2676
  <div class="__crossx-rows">
2677
- ${ee((t==null?void 0:t.label_to)??"To",c)}
2678
- ${ee((t==null?void 0:t.label_network)??"Network",`<span>${tn(s.chainId)}</span>`)}
2677
+ ${Z((t==null?void 0:t.label_to)??"To",c)}
2678
+ ${Z((t==null?void 0:t.label_network)??"Network",`<span>${rn(s.chainId)}</span>`)}
2679
2679
  ${l}
2680
2680
  </div>
2681
2681
  <div class="__crossx-pill">
@@ -2686,17 +2686,17 @@ button.__crossx-connect-other-block:active {
2686
2686
  <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${v(_)}</button>
2687
2687
  </div>
2688
2688
  </div>
2689
- `,f}function At(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function v(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Na(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function Pa(s){if(typeof s=="string")return v(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return v(JSON.stringify(s))}catch{return String(s)}}function Oa(s){return s.includes(":")?s.split(":")[1]??s:s}function La(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function Da(s,e){return`https://explorer.crosstoken.io/${Oa(s)}/tx/${e}`}function nn(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${v(e)}" target="_blank" rel="noopener noreferrer">${v(s)}</a>`}function It(s){return nn(Ie(s),La(s))}function on(s,e){return nn(Ie(e),Da(s,e))}function Ba(s,e,r){const t=ee((r==null?void 0:r.label_from)??"From",`${It(s.from)}
2690
- <button class="__crossx-copy-btn" data-copy="${v(s.from)}" title="Copy address">${Te}</button>`),n=s.to?ee((r==null?void 0:r.label_to)??"To",`${It(s.to)}
2691
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`):"",i=s.amount?ee((r==null?void 0:r.label_transfer)??"Transfer",`<span>${v(s.amount)}</span>`):"",o=s.fees?ee((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${v(s.fees)}</span>`):"",a=s.txHash?ee((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${on(s.chainId,s.txHash)}
2689
+ `,f}function At(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function v(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Da(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function Ba(s){if(typeof s=="string")return v(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return v(JSON.stringify(s))}catch{return String(s)}}function Ma(s){return s.includes(":")?s.split(":")[1]??s:s}function $a(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function Fa(s,e){return`https://explorer.crosstoken.io/${Ma(s)}/tx/${e}`}function on(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${v(e)}" target="_blank" rel="noopener noreferrer">${v(s)}</a>`}function It(s){return on(Ie(s),$a(s))}function an(s,e){return on(Ie(e),Fa(s,e))}function Wa(s,e,r){const t=Z((r==null?void 0:r.label_from)??"From",`${It(s.from)}
2690
+ <button class="__crossx-copy-btn" data-copy="${v(s.from)}" title="Copy address">${Te}</button>`),n=s.to?Z((r==null?void 0:r.label_to)??"To",`${It(s.to)}
2691
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`):"",i=s.amount?Z((r==null?void 0:r.label_transfer)??"Transfer",`<span>${v(s.amount)}</span>`):"",o=s.fees?Z((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${v(s.fees)}</span>`):"",a=s.txHash?Z((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${an(s.chainId,s.txHash)}
2692
2692
  <button class="__crossx-copy-btn" data-copy="${v(s.txHash)}" title="Copy hash">${Te}</button>`):"",c=s.total?`<div class="__crossx-total-pill">
2693
2693
  <span class="__crossx-total-label">${v((r==null?void 0:r.label_total)??"Total")}<br>${v((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
2694
2694
  <span class="__crossx-total-amount">${v(s.total)}</span>
2695
- </div>`:"",l=document.createElement("div");return l.id=re,l.innerHTML=`
2695
+ </div>`:"",l=document.createElement("div");return l.id=ee,l.innerHTML=`
2696
2696
  <div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2697
2697
  <div class="__crossx-header">
2698
2698
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
2699
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2699
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2700
2700
  </div>
2701
2701
  <hr class="__crossx-divider">
2702
2702
  <div class="__crossx-body">
@@ -2711,7 +2711,7 @@ button.__crossx-connect-other-block:active {
2711
2711
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
2712
2712
  </div>
2713
2713
  </div>
2714
- `,l}function Ma(s,e,r){const t=document.createElement("div");return t.id=re,t.innerHTML=`
2714
+ `,l}function Ua(s,e,r){const t=document.createElement("div");return t.id=ee,t.innerHTML=`
2715
2715
  <div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2716
2716
  <div class="__crossx-header">
2717
2717
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
@@ -2724,9 +2724,9 @@ button.__crossx-connect-other-block:active {
2724
2724
  </div>
2725
2725
  </div>
2726
2726
  </div>
2727
- `,t}function $a(s,e,r,t){const n=e.status!=="reverted"&&e.status!=="timeout",i=e.status==="timeout",o=s.querySelector("#__crossx-ttl"),a=s.querySelector(".__crossx-header");if(o){const w=i?Aa:n?"":Ea,b=i?(t==null?void 0:t.tx_timeout)??"Transaction timeout":n?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${v(b)}</span>`):o.textContent=b}if(a&&!s.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ie,a.appendChild(w)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?ee((t==null?void 0:t.label_from)??"From",`${It(e.from)}
2728
- <button class="__crossx-copy-btn" data-copy="${v(e.from)}" title="Copy address">${Te}</button>`):"",u=e.to?ee((t==null?void 0:t.label_to)??"To",`${It(e.to)}
2729
- <button class="__crossx-copy-btn" data-copy="${v(e.to)}" title="Copy address">${Te}</button>`):"",h=e.amount?ee((t==null?void 0:t.label_transfer)??"Transfer",`<span>${v(e.amount)}</span>`):"",_=e.fees?ee((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${v(e.fees)}</span>`):"",f=e.txHash?ee((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${on(e.chainId,e.txHash)}
2727
+ `,t}function Ha(s,e,r,t){const n=e.status!=="reverted"&&e.status!=="timeout",i=e.status==="timeout",o=s.querySelector("#__crossx-ttl"),a=s.querySelector(".__crossx-header");if(o){const w=i?ka:n?"":Ra,b=i?(t==null?void 0:t.tx_timeout)??"Transaction timeout":n?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${v(b)}</span>`):o.textContent=b}if(a&&!s.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ne,a.appendChild(w)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?Z((t==null?void 0:t.label_from)??"From",`${It(e.from)}
2728
+ <button class="__crossx-copy-btn" data-copy="${v(e.from)}" title="Copy address">${Te}</button>`):"",u=e.to?Z((t==null?void 0:t.label_to)??"To",`${It(e.to)}
2729
+ <button class="__crossx-copy-btn" data-copy="${v(e.to)}" title="Copy address">${Te}</button>`):"",h=e.amount?Z((t==null?void 0:t.label_transfer)??"Transfer",`<span>${v(e.amount)}</span>`):"",_=e.fees?Z((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${v(e.fees)}</span>`):"",f=e.txHash?Z((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${an(e.chainId,e.txHash)}
2730
2730
  <button class="__crossx-copy-btn" data-copy="${v(e.txHash)}" title="Copy hash">${Te}</button>`):"",x=e.total?`<div class="__crossx-total-pill">
2731
2731
  <span class="__crossx-total-label">${v((t==null?void 0:t.label_total)??"Total")}<br>${v((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
2732
2732
  <span class="__crossx-total-amount">${v(e.total)}</span>
@@ -2740,11 +2740,11 @@ button.__crossx-connect-other-block:active {
2740
2740
  </div>
2741
2741
  ${x}
2742
2742
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((t==null?void 0:t.tx_complete_done_button)??(n?"All Done":"Done"))}</button>
2743
- `,c.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",b=>{var R;b.stopPropagation();const A=w.dataset.copy;A&&((R=navigator.clipboard)==null||R.writeText(A).catch(()=>{}))})})}function Fa(s,e,r){const t=e,n=At(s.dappName),i=v(s.message),o=document.createElement("div");return o.id=re,o.innerHTML=`
2743
+ `,c.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",b=>{var R;b.stopPropagation();const A=w.dataset.copy;A&&((R=navigator.clipboard)==null||R.writeText(A).catch(()=>{}))})})}function Ga(s,e,r){const t=e,n=At(s.dappName),i=v(s.message),o=document.createElement("div");return o.id=ee,o.innerHTML=`
2744
2744
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2745
2745
  <div class="__crossx-header">
2746
2746
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
2747
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2747
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2748
2748
  </div>
2749
2749
  <hr class="__crossx-divider">
2750
2750
  <div class="__crossx-body">
@@ -2754,7 +2754,7 @@ button.__crossx-connect-other-block:active {
2754
2754
  <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2755
2755
  </p>
2756
2756
  <div class="__crossx-addr-pill">
2757
- ${_r}
2757
+ ${gr}
2758
2758
  <span class="__crossx-addr-pill-text">${Ie(s.from)}</span>
2759
2759
  </div>
2760
2760
  <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
@@ -2768,20 +2768,20 @@ button.__crossx-connect-other-block:active {
2768
2768
  </div>
2769
2769
  </div>
2770
2770
  </div>
2771
- `,o}function Wa(s,e,r){const t=e,n=At(s.dappName);let i={};if(typeof s.typedData=="string")try{i=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(i=s.typedData);const o=i.primaryType??"—",a=i.message??{};let c=`
2771
+ `,o}function Ka(s,e,r){const t=e,n=At(s.dappName);let i={};if(typeof s.typedData=="string")try{i=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(i=s.typedData);const o=i.primaryType??"—",a=i.message??{};let c=`
2772
2772
  <div class="__crossx-td-row">
2773
2773
  <span class="__crossx-td-label">${v((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
2774
2774
  <span class="__crossx-td-value">${v(o)}</span>
2775
- </div>`;for(const[u,h]of Object.entries(a)){const _=Pa(h),x=Na(h)?`<span class="__crossx-addr-text">${Ie(h)}</span>
2775
+ </div>`;for(const[u,h]of Object.entries(a)){const _=Ba(h),x=Da(h)?`<span class="__crossx-addr-text">${Ie(h)}</span>
2776
2776
  <button class="__crossx-copy-btn" data-copy="${v(String(h))}" title="Copy">${Te}</button>`:`<span>${_}</span>`;c+=`
2777
2777
  <div class="__crossx-td-row">
2778
2778
  <span class="__crossx-td-label">${v(u)}</span>
2779
2779
  <div class="__crossx-td-value">${x}</div>
2780
- </div>`}const l=document.createElement("div");return l.id=re,l.innerHTML=`
2780
+ </div>`}const l=document.createElement("div");return l.id=ee,l.innerHTML=`
2781
2781
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2782
2782
  <div class="__crossx-header">
2783
2783
  <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
2784
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2784
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2785
2785
  </div>
2786
2786
  <hr class="__crossx-divider">
2787
2787
  <div class="__crossx-body">
@@ -2791,7 +2791,7 @@ button.__crossx-connect-other-block:active {
2791
2791
  <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2792
2792
  </p>
2793
2793
  <div class="__crossx-addr-pill">
2794
- ${_r}
2794
+ ${gr}
2795
2795
  <span class="__crossx-addr-pill-text">${Ie(s.from)}</span>
2796
2796
  </div>
2797
2797
  <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
@@ -2805,12 +2805,12 @@ button.__crossx-connect-other-block:active {
2805
2805
  </div>
2806
2806
  </div>
2807
2807
  </div>
2808
- `,l}const Ua=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2808
+ `,l}const qa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2809
2809
  <line x1="12" y1="5" x2="12" y2="19"/>
2810
2810
  <line x1="5" y1="12" x2="19" y2="12"/>
2811
- </svg>`,Ha='<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 an(s){return s.name||`Account ${s.index+1}`}function Ga(){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">${sn}</g></svg>`}const Ka=Ot().portraitBaseUrl;function qa(s,e){const r=e.replace("#","");return`${Ka}/portrait/evm/${s}.png?size=256&bg=${r}`}function cn(s,e,r){const t=qa(s,r),i=Ga().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='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function Va(s,e,r,t){const n=r==null?void 0:r.toLowerCase(),i=s.map(a=>{const c=n&&a.address.toLowerCase()===n,l=c?" __crossx-wallet-item--selected":"",u=c?`<span class="__crossx-wallet-selected">${v((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${Ha}</span>`:"";return`<button class="__crossx-wallet-item${l}" data-wallet-index="${a.index}" data-wallet-address="${v(a.address)}">
2812
- ${cn(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(an(a))}</span><span class="__crossx-wallet-addr">${Xs(a.address)}</span></span>${u}
2813
- </button>`}).join(""),o=document.createElement("div");return o.id=re,o.className="__crossx-overlay--wallet-selector",o.innerHTML=`
2811
+ </svg>`,Va='<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 cn(s){return s.name||`Account ${s.index+1}`}function za(){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">${nn}</g></svg>`}const Ja=Pt().portraitBaseUrl;function ja(s,e){const r=e.replace("#","");return`${Ja}/portrait/evm/${s}.png?size=256&bg=${r}`}function ln(s,e,r){const t=ja(s,r),i=za().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='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function Ya(s,e,r,t){const n=r==null?void 0:r.toLowerCase(),i=s.map(a=>{const c=n&&a.address.toLowerCase()===n,l=c?" __crossx-wallet-item--selected":"",u=c?`<span class="__crossx-wallet-selected">${v((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${Va}</span>`:"";return`<button class="__crossx-wallet-item${l}" data-wallet-index="${a.index}" data-wallet-address="${v(a.address)}">
2812
+ ${ln(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(cn(a))}</span><span class="__crossx-wallet-addr">${Zs(a.address)}</span></span>${u}
2813
+ </button>`}).join(""),o=document.createElement("div");return o.id=ee,o.className="__crossx-overlay--wallet-selector",o.innerHTML=`
2814
2814
  <div class="__crossx-card __crossx-card--wallet-selector" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2815
2815
  <div class="__crossx-header">
2816
2816
  <span class="__crossx-wallet-sheet-handle" aria-hidden="true"></span>
@@ -2818,7 +2818,7 @@ button.__crossx-connect-other-block:active {
2818
2818
  <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
2819
2819
  <p class="__crossx-subtitle--body">${v((t==null?void 0:t.wallet_selector_description)??"Please select the wallet you previously used for this game to continue.")}</p>
2820
2820
  </div>
2821
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2821
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2822
2822
  </div>
2823
2823
  <hr class="__crossx-divider">
2824
2824
  <div class="__crossx-body __crossx-wallet-selector-body">
@@ -2827,7 +2827,7 @@ button.__crossx-connect-other-block:active {
2827
2827
  ${i}
2828
2828
  </div>
2829
2829
  <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2830
- <span class="__crossx-wallet-add-icon">${Ua}</span>
2830
+ <span class="__crossx-wallet-add-icon">${qa}</span>
2831
2831
  <span class="__crossx-wallet-add-label">${v((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
2832
2832
  </button>
2833
2833
  <p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
@@ -2840,41 +2840,41 @@ button.__crossx-connect-other-block:active {
2840
2840
  </div>
2841
2841
  </div>
2842
2842
  </div>
2843
- `,o}function za(s,e){const r=document.createElement("div");r.id=re;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Ia(t,s),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const n=document.createElement("div");n.className="__crossx-header";const i=document.createElement("span");i.className="__crossx-wallet-created-sheet-handle",i.ariaHidden="true";const o=document.createElement("p");o.className="__crossx-title",o.id="__crossx-ttl",o.style.paddingRight="48px",o.textContent=(e==null?void 0:e.wallet_created_title)??"Wallet Created!";const a=document.createElement("button");a.className="__crossx-close",a.id="__crossx-close-btn",a.type="button",a.ariaLabel="Close",a.innerHTML=ie,n.append(i,o,a);const c=document.createElement("hr");c.className="__crossx-divider";const l=document.createElement("div");l.className="__crossx-wallet-created-body";const u=document.createElement("div");u.className="__crossx-wallet-created-hero";const h=document.createElement("span");h.className="__crossx-wallet-created-illust",h.ariaHidden="true";const _=w=>{const b=document.createElement("span");return b.className=w,b};h.append(_("__crossx-wallet-created-shadow"),_("__crossx-wallet-created-wallet"),_("__crossx-wallet-created-coin"),_("__crossx-wallet-created-burst"),_("__crossx-wallet-created-pointer"),_("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--purple"),_("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--teal"),_("__crossx-wallet-created-dot __crossx-wallet-created-dot--one"),_("__crossx-wallet-created-dot __crossx-wallet-created-dot--two")),u.appendChild(h),l.appendChild(u);const f=document.createElement("div");f.className="__crossx-wallet-created-footer";const x=document.createElement("button");return x.className="__crossx-wallet-created-btn",x.id="__crossx-wallet-created-done",x.type="button",x.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",f.appendChild(x),t.append(n,c,l,f),r.appendChild(t),r}const Ja=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2843
+ `,o}function Xa(s,e){const r=document.createElement("div");r.id=ee;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Ca(t,s),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const n=document.createElement("div");n.className="__crossx-header";const i=document.createElement("span");i.className="__crossx-wallet-created-sheet-handle",i.ariaHidden="true";const o=document.createElement("p");o.className="__crossx-title",o.id="__crossx-ttl",o.style.paddingRight="48px",o.textContent=(e==null?void 0:e.wallet_created_title)??"Wallet Created!";const a=document.createElement("button");a.className="__crossx-close",a.id="__crossx-close-btn",a.type="button",a.ariaLabel="Close",a.innerHTML=ne,n.append(i,o,a);const c=document.createElement("hr");c.className="__crossx-divider";const l=document.createElement("div");l.className="__crossx-wallet-created-body";const u=document.createElement("div");u.className="__crossx-wallet-created-hero";const h=document.createElement("span");h.className="__crossx-wallet-created-illust",h.ariaHidden="true";const _=w=>{const b=document.createElement("span");return b.className=w,b};h.append(_("__crossx-wallet-created-shadow"),_("__crossx-wallet-created-wallet"),_("__crossx-wallet-created-coin"),_("__crossx-wallet-created-burst"),_("__crossx-wallet-created-pointer"),_("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--purple"),_("__crossx-wallet-created-sparkle __crossx-wallet-created-sparkle--teal"),_("__crossx-wallet-created-dot __crossx-wallet-created-dot--one"),_("__crossx-wallet-created-dot __crossx-wallet-created-dot--two")),u.appendChild(h),l.appendChild(u);const f=document.createElement("div");f.className="__crossx-wallet-created-footer";const x=document.createElement("button");return x.className="__crossx-wallet-created-btn",x.id="__crossx-wallet-created-done",x.type="button",x.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",f.appendChild(x),t.append(n,c,l,f),r.appendChild(t),r}const Za=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2844
2844
  <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"/>
2845
2845
  <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"/>
2846
- </svg>`,ja=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2846
+ </svg>`,Qa=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2847
2847
  <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"/>
2848
2848
  <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"/>
2849
2849
  <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"/>
2850
2850
  <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"/>
2851
- </svg>`;function Ya(s){const e=Er(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${va[s]??""}</span><span class="__crossx-connect-other-wallet-name">${v(e)}</span></span>`}function Xa(s){if(s.length===0)return"";const e=n=>Ya(s[n]),r="Supported wallets include ";if(s.length===1)return`${r}${e(0)}.`;if(s.length===2)return`${r}${e(0)} and ${e(1)}.`;if(s.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=s.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function Za(s,e=[],r){const t=s,n=v(String(e[0])),i=v((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
2851
+ </svg>`;function ec(s){const e=Ar(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Ta[s]??""}</span><span class="__crossx-connect-other-wallet-name">${v(e)}</span></span>`}function tc(s){if(s.length===0)return"";const e=n=>ec(s[n]),r="Supported wallets include ";if(s.length===1)return`${r}${e(0)}.`;if(s.length===2)return`${r}${e(0)} and ${e(1)}.`;if(s.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=s.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function rc(s,e=[],r){const t=s,n=v(String(e[0])),i=v((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
2852
2852
  <div class="__crossx-login-or-divider">
2853
2853
  <hr><span>${i}</span><hr>
2854
2854
  </div>
2855
2855
  <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${n}" aria-labelledby="__crossx-connect-other-heading">
2856
2856
  <span class="__crossx-connect-other-text">
2857
2857
  <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${v((r==null?void 0:r.login_selector_connect_other_wallets)??"Connect with Other Wallets")}</span>
2858
- <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${Xa(e)}</span>
2858
+ <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${tc(e)}</span>
2859
2859
  </span>
2860
- </button>`:"",a=document.createElement("div");return a.id=re,a.innerHTML=`
2860
+ </button>`:"",a=document.createElement("div");return a.id=ee,a.innerHTML=`
2861
2861
  <div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2862
2862
  <div class="__crossx-header">
2863
2863
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
2864
2864
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${v((r==null?void 0:r.login_selector_title)??at)}</p>
2865
2865
  <p class="__crossx-subtitle">${v((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
2866
2866
  </div>
2867
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2867
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2868
2868
  </div>
2869
2869
  <hr class="__crossx-divider">
2870
2870
  <div class="__crossx-body">
2871
2871
  <div class="__crossx-login-btn-row">
2872
2872
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
2873
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${Ja}</span>
2873
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${Za}</span>
2874
2874
  <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
2875
2875
  </button>
2876
2876
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
2877
- <span class="__crossx-login-icon">${ja}</span>
2877
+ <span class="__crossx-login-icon">${Qa}</span>
2878
2878
  <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
2879
2879
  </button>
2880
2880
  </div>${o}
@@ -2883,14 +2883,14 @@ button.__crossx-connect-other-block:active {
2883
2883
  </p>
2884
2884
  </div>
2885
2885
  </div>
2886
- `,a}function Qa(s,e){const r=s,t=document.createElement("div");t.id=re;const n=v(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
2886
+ `,a}function sc(s,e){const r=s,t=document.createElement("div");t.id=ee;const n=v(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
2887
2887
  <p class="__crossx-session-account-label">${v(e.accountLabel)}</p>
2888
2888
  <p class="__crossx-session-account-email">${v(e.email)}</p>
2889
2889
  </div>`:"";return t.innerHTML=`
2890
2890
  <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
2891
2891
  <div class="__crossx-header">
2892
2892
  <p class="__crossx-title" id="__crossx-session-header-title">${v(e.title)}</p>
2893
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2893
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2894
2894
  </div>
2895
2895
  <hr class="__crossx-divider">
2896
2896
  <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
@@ -2905,7 +2905,7 @@ button.__crossx-connect-other-block:active {
2905
2905
  </div>
2906
2906
  </div>
2907
2907
  </div>
2908
- `,t}function ec(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=re,i.innerHTML=`
2908
+ `,t}function nc(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=ee,i.innerHTML=`
2909
2909
  <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2910
2910
  <div class="__crossx-header">
2911
2911
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
@@ -2919,17 +2919,17 @@ button.__crossx-connect-other-block:active {
2919
2919
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
2920
2920
  </div>
2921
2921
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
2922
- <span class="__crossx-recover-icon">${ma}</span>
2922
+ <span class="__crossx-recover-icon">${va}</span>
2923
2923
  <span class="__crossx-recover-label">Import from Social Backup</span>
2924
2924
  </button>
2925
2925
  ${n}
2926
2926
  </div>
2927
2927
  </div>
2928
- `,i}function tc(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",h=document.createElement("div");return h.id=re,h.innerHTML=`
2928
+ `,i}function ic(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",h=document.createElement("div");return h.id=ee,h.innerHTML=`
2929
2929
  <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2930
2930
  <div class="__crossx-header">
2931
2931
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2932
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2932
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2933
2933
  </div>
2934
2934
  <hr class="__crossx-divider">
2935
2935
  <div class="__crossx-pin-center">
@@ -2945,11 +2945,11 @@ button.__crossx-connect-other-block:active {
2945
2945
  ${u}
2946
2946
  </div>
2947
2947
  </div>
2948
- `,h}function rc(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function sc(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?rc(i):null,a=document.createElement("div");return a.id=re,a.innerHTML=`
2948
+ `,h}function oc(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function ac(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?oc(i):null,a=document.createElement("div");return a.id=ee,a.innerHTML=`
2949
2949
  <div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2950
2950
  <div class="__crossx-header">
2951
2951
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2952
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2952
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2953
2953
  </div>
2954
2954
  <hr class="__crossx-divider">
2955
2955
  <div class="__crossx-pin-center">
@@ -2965,9 +2965,9 @@ button.__crossx-connect-other-block:active {
2965
2965
  </div>
2966
2966
  </div>
2967
2967
  </div>
2968
- `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const h=setInterval(()=>{Date.now()>=i&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function nc(s){const r=[s.check1,s.check2].map((t,n)=>`
2968
+ `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const h=setInterval(()=>{Date.now()>=i&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function cc(s){const r=[s.check1,s.check2].map((t,n)=>`
2969
2969
  <div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
2970
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${cc}</div>
2970
+ <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${hc}</div>
2971
2971
  <span class="__crossx-pw-notice-item-text">${v(t)}</span>
2972
2972
  </div>
2973
2973
  `).join("");return`
@@ -2975,14 +2975,14 @@ button.__crossx-connect-other-block:active {
2975
2975
  <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
2976
2976
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
2977
2977
  <p class="__crossx-pw-subtitle">${v(s.headerSubtitle)}</p>
2978
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2978
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2979
2979
  </div>
2980
2980
  <hr class="__crossx-divider">
2981
2981
  <div class="__crossx-pw-body">
2982
2982
  <div class="__crossx-pw-fields __crossx-pw-fields--notice">
2983
2983
  <div class="__crossx-pw-notice-header">
2984
2984
  <div class="__crossx-pw-notice-title-row">
2985
- <span class="__crossx-pw-notice-icon">${lc}</span>
2985
+ <span class="__crossx-pw-notice-icon">${pc}</span>
2986
2986
  <p class="__crossx-pw-notice-title">${v(s.noticeTitle)}</p>
2987
2987
  </div>
2988
2988
  <p class="__crossx-pw-notice-desc">${v(s.noticeDesc)}</p>
@@ -3000,8 +3000,8 @@ button.__crossx-connect-other-block:active {
3000
3000
  </button>
3001
3001
  </div>
3002
3002
  <div class="__crossx-home-indicator"></div>
3003
- `}function gr(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${v(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${v(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${v(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
3004
- ${dn}
3003
+ `}function xr(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${v(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${v(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${v(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
3004
+ ${un}
3005
3005
  <span id="__crossx-pin6-lock-countdown"></span>
3006
3006
  </p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${v(s.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(w,b)=>`<input class="__crossx-pin6-box${l}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-label="PIN digit ${b+1}"${e?" disabled":""}>`).join(""),h=e?" --locked":"",_=Array.from({length:6},(w,b)=>`<div class="__crossx-pin6-dot${h}" data-dot-index="${b}" aria-label="PIN digit ${b+1}"></div>`).join(""),f=e?" --disabled":"",x=`
3007
3007
  <div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
@@ -3023,14 +3023,14 @@ button.__crossx-connect-other-block:active {
3023
3023
  <div class="__crossx-pin6-numpad-row">
3024
3024
  <button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
3025
3025
  <button type="button" class="__crossx-pin6-numpad-key${f}" data-key="0">0</button>
3026
- <button type="button" class="__crossx-pin6-numpad-key --delete${f}" data-key="backspace" aria-label="Delete">${ac}</button>
3026
+ <button type="button" class="__crossx-pin6-numpad-key --delete${f}" data-key="backspace" aria-label="Delete">${uc}</button>
3027
3027
  </div>
3028
3028
  </div>`;return`
3029
3029
  <div class="__crossx-header">
3030
3030
  <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
3031
3031
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
3032
3032
  ${t}
3033
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3033
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
3034
3034
  </div>
3035
3035
  <hr class="__crossx-divider">
3036
3036
  <div class="__crossx-pin6-body"${r}>
@@ -3047,20 +3047,20 @@ button.__crossx-connect-other-block:active {
3047
3047
  ${o}
3048
3048
  </div>
3049
3049
  ${x}
3050
- `}function ln(s,e){const r=document.createElement("div");return r.id=re,r.innerHTML=`
3050
+ `}function dn(s,e){const r=document.createElement("div");return r.id=ee,r.innerHTML=`
3051
3051
  <div class="__crossx-card __crossx-card--pin6" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3052
3052
  ${e}
3053
3053
  </div>
3054
- `,r}function ic(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function oc(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function xr(s,e,r,t,n,i,o){var P,H;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),u=()=>s.querySelector("#__crossx-pin6-boxes"),h=()=>s.querySelector("#__crossx-pin6-error"),_=()=>s.querySelector("#__crossx-pin6-lock-msg"),f=()=>s.querySelector("#__crossx-pin6-lock-countdown"),x=()=>s.querySelector(".__crossx-pin6-body"),w="●",b=(S,E)=>{S.dataset.digit=E,S.value=w},A=S=>{delete S.dataset.digit,S.value=""},R=S=>S.dataset.digit??"",k=()=>l().map(R).join(""),L=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),U=()=>{var C;const S=l(),E=L();if(E.length&&(E.forEach((I,W)=>{const q=!!(S[W]&&R(S[W]));I.classList.toggle("--filled",q),I.classList.toggle("--active",!1)}),!a&&!c)){const I=S.findIndex(q=>!R(q));(C=E[I===-1?5:I])==null||C.classList.add("--active")}},G=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(E=>E.classList.toggle("--disabled",a)),L().forEach(E=>E.classList.toggle("--locked",a)),U()},ae=S=>{a=S,l().forEach(E=>{E.disabled=S,E.classList.toggle("--locked",S)})},Y=()=>s.querySelector("#__crossx-pin6-attempt"),X=()=>{const S=h();S&&(S.textContent="")},V=()=>o??"Your account will be locked after further failures.",K=()=>s.querySelector("#__crossx-pin6-warning"),B=S=>{var C;let E=K();if(!E){E=document.createElement("p"),E.className="__crossx-pin6-warning",E.id="__crossx-pin6-warning";const I=h();I?I.insertAdjacentElement("afterend",E):(C=x())==null||C.appendChild(E)}E.textContent=S},F=()=>{const S=K();S&&(S.textContent="")},m=(S,E)=>{var I;let C=Y();if(!C){C=document.createElement("p"),C.className="__crossx-pin6-attempt",C.id="__crossx-pin6-attempt";const W=K()??h();W?W.insertAdjacentElement("afterend",C):(I=x())==null||I.appendChild(C)}C.textContent=`${S}/${E}`},y=()=>{const S=Y();S&&(S.textContent="")},T=S=>{const E=h();E&&(E.textContent=S);const C=u();C==null||C.classList.add("--shake"),setTimeout(()=>C==null?void 0:C.classList.remove("--shake"),500),l().forEach(A),setTimeout(()=>{var I;(I=l()[0])==null||I.focus(),U()},50)},N=S=>{var q;ae(!0),l().forEach(A),G();const E=h();if(E&&(E.textContent="Too many failed attempts. Please wait."),!_()){const J=document.createElement("p");J.className="__crossx-pin6-lock-msg",J.id="__crossx-pin6-lock-msg",J.innerHTML=`${dn}<span id="__crossx-pin6-lock-countdown"></span>`;const z=h();z?z.insertAdjacentElement("afterend",J):(q=x())==null||q.appendChild(J)}const C=()=>{var Z;const J=S-Date.now(),z=f();J<=0?(clearInterval(I),ae(!1),(Z=_())==null||Z.remove(),E&&(E.textContent=""),G(),setTimeout(()=>{var We;return(We=l()[0])==null?void 0:We.focus()},50)):z&&(z.textContent=` ${oc(J)}`)},I=setInterval(C,1e3);C();const W=new MutationObserver(()=>{document.contains(s)||(clearInterval(I),W.disconnect())});W.observe(document.body,{childList:!0,subtree:!1})},M=async()=>{if(a||c)return;const S=k();if(S.length===6){c=!0,l().forEach(E=>{E.disabled=!0});try{if(n){const E=await n(S);E.ok?e(S):E.lockExpiresAt?(y(),N(E.lockExpiresAt)):(T(E.error??"Incorrect PIN. Please try again."),E.attemptCount!=null&&E.maxAttempts!=null?(B(V()),m(E.attemptCount,E.maxAttempts)):(F(),y()))}else e(S)}catch(E){t&&t(E)}finally{c=!1,a||l().forEach(E=>{E.disabled=!1}),U()}}};i&&i>Date.now()?N(i):setTimeout(()=>{var S;return(S=l()[0])==null?void 0:S.focus()},100);const D=()=>{if(a||c)return;const S=l(),E=S.find(C=>!R(C))??S[S.length-1];E==null||E.focus()};(P=u())==null||P.addEventListener("click",S=>{S.target.classList.contains("__crossx-pin6-box")||D()}),(H=x())==null||H.addEventListener("click",S=>{const E=S.target;E.classList.contains("__crossx-pin6-box")||E.closest("button")||D()}),l().forEach((S,E)=>{S.addEventListener("input",()=>{var I;const C=S.value.replace(/\D/g,"").slice(-1);C?b(S,C):A(S),X(),C&&E<5&&((I=l()[E+1])==null||I.focus()),U(),k().length===6&&setTimeout(M,80)}),S.addEventListener("keydown",C=>{var I,W;if(C.key==="Backspace"){if(C.preventDefault(),R(S))A(S);else if(E>0){const q=l()[E-1];A(q),q.focus()}U()}else C.key==="ArrowLeft"&&E>0?(C.preventDefault(),(I=l()[E-1])==null||I.focus()):C.key==="ArrowRight"&&E<5?(C.preventDefault(),(W=l()[E+1])==null||W.focus()):C.key==="Escape"&&r()}),S.addEventListener("paste",C=>{var q,J;C.preventDefault();const I=(((q=C.clipboardData)==null?void 0:q.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const W=l();I.split("").forEach((z,Z)=>{W[Z]&&b(W[Z],z)}),(J=W[Math.min(I.length-1,5)])==null||J.focus(),X(),U(),k().length===6&&setTimeout(M,80)}),S.addEventListener("focus",()=>S.select())});const $=s.querySelector("#__crossx-pin6-numpad");if($){let S=null;const E=()=>{S&&(S.classList.remove("--pressed"),S=null)};$.addEventListener("pointerdown",I=>{const W=I.target.closest(".__crossx-pin6-numpad-key");!W||a||c||(E(),S=W,W.classList.add("--pressed"),W.setPointerCapture(I.pointerId))});const C=I=>{const W=I.dataset.key;if(!W)return;if(W==="backspace"){const Z=[...l()].reverse().find(We=>R(We));Z&&(A(Z),X()),U();return}if(!/^\d$/.test(W))return;const J=l().find(z=>!R(z));J&&(b(J,W),X(),U(),k().length===6&&setTimeout(M,80))};$.addEventListener("pointerup",I=>{if(!S)return;const W=S;E();const q=W.getBoundingClientRect();I.clientX>=q.left&&I.clientX<=q.right&&I.clientY>=q.top&&I.clientY<=q.bottom&&!a&&!c&&C(W)}),$.addEventListener("pointercancel",E),$.addEventListener("pointerleave",E,!0),U(),i&&i>Date.now()&&G()}}const ac=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3054
+ `,r}function lc(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function dc(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function wr(s,e,r,t,n,i,o){var O,G;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),u=()=>s.querySelector("#__crossx-pin6-boxes"),h=()=>s.querySelector("#__crossx-pin6-error"),_=()=>s.querySelector("#__crossx-pin6-lock-msg"),f=()=>s.querySelector("#__crossx-pin6-lock-countdown"),x=()=>s.querySelector(".__crossx-pin6-body"),w="●",b=(S,E)=>{S.dataset.digit=E,S.value=w},A=S=>{delete S.dataset.digit,S.value=""},R=S=>S.dataset.digit??"",C=()=>l().map(R).join(""),D=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),H=()=>{var k;const S=l(),E=D();if(E.length&&(E.forEach((I,U)=>{const q=!!(S[U]&&R(S[U]));I.classList.toggle("--filled",q),I.classList.toggle("--active",!1)}),!a&&!c)){const I=S.findIndex(q=>!R(q));(k=E[I===-1?5:I])==null||k.classList.add("--active")}},K=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(E=>E.classList.toggle("--disabled",a)),D().forEach(E=>E.classList.toggle("--locked",a)),H()},re=S=>{a=S,l().forEach(E=>{E.disabled=S,E.classList.toggle("--locked",S)})},ie=()=>s.querySelector("#__crossx-pin6-attempt"),V=()=>{const S=h();S&&(S.textContent="")},oe=()=>o??"Your account will be locked after further failures.",L=()=>s.querySelector("#__crossx-pin6-warning"),F=S=>{var k;let E=L();if(!E){E=document.createElement("p"),E.className="__crossx-pin6-warning",E.id="__crossx-pin6-warning";const I=h();I?I.insertAdjacentElement("afterend",E):(k=x())==null||k.appendChild(E)}E.textContent=S},W=()=>{const S=L();S&&(S.textContent="")},m=(S,E)=>{var I;let k=ie();if(!k){k=document.createElement("p"),k.className="__crossx-pin6-attempt",k.id="__crossx-pin6-attempt";const U=L()??h();U?U.insertAdjacentElement("afterend",k):(I=x())==null||I.appendChild(k)}k.textContent=`${S}/${E}`},y=()=>{const S=ie();S&&(S.textContent="")},T=S=>{const E=h();E&&(E.textContent=S);const k=u();k==null||k.classList.add("--shake"),setTimeout(()=>k==null?void 0:k.classList.remove("--shake"),500),l().forEach(A),setTimeout(()=>{var I;(I=l()[0])==null||I.focus(),H()},50)},N=S=>{var q;re(!0),l().forEach(A),K();const E=h();if(E&&(E.textContent="Too many failed attempts. Please wait."),!_()){const J=document.createElement("p");J.className="__crossx-pin6-lock-msg",J.id="__crossx-pin6-lock-msg",J.innerHTML=`${un}<span id="__crossx-pin6-lock-countdown"></span>`;const z=h();z?z.insertAdjacentElement("afterend",J):(q=x())==null||q.appendChild(J)}const k=()=>{var Y;const J=S-Date.now(),z=f();J<=0?(clearInterval(I),re(!1),(Y=_())==null||Y.remove(),E&&(E.textContent=""),K(),setTimeout(()=>{var We;return(We=l()[0])==null?void 0:We.focus()},50)):z&&(z.textContent=` ${dc(J)}`)},I=setInterval(k,1e3);k();const U=new MutationObserver(()=>{document.contains(s)||(clearInterval(I),U.disconnect())});U.observe(document.body,{childList:!0,subtree:!1})},$=async()=>{if(a||c)return;const S=C();if(S.length===6){c=!0,l().forEach(E=>{E.disabled=!0});try{if(n){const E=await n(S);E.ok?e(S):E.lockExpiresAt?(y(),N(E.lockExpiresAt)):(T(E.error??"Incorrect PIN. Please try again."),E.attemptCount!=null&&E.maxAttempts!=null?(F(oe()),m(E.attemptCount,E.maxAttempts)):(W(),y()))}else e(S)}catch(E){t&&t(E)}finally{c=!1,a||l().forEach(E=>{E.disabled=!1}),H()}}};i&&i>Date.now()?N(i):setTimeout(()=>{var S;return(S=l()[0])==null?void 0:S.focus()},100);const B=()=>{if(a||c)return;const S=l(),E=S.find(k=>!R(k))??S[S.length-1];E==null||E.focus()};(O=u())==null||O.addEventListener("click",S=>{S.target.classList.contains("__crossx-pin6-box")||B()}),(G=x())==null||G.addEventListener("click",S=>{const E=S.target;E.classList.contains("__crossx-pin6-box")||E.closest("button")||B()}),l().forEach((S,E)=>{S.addEventListener("input",()=>{var I;const k=S.value.replace(/\D/g,"").slice(-1);k?b(S,k):A(S),V(),k&&E<5&&((I=l()[E+1])==null||I.focus()),H(),C().length===6&&setTimeout($,80)}),S.addEventListener("keydown",k=>{var I,U;if(k.key==="Backspace"){if(k.preventDefault(),R(S))A(S);else if(E>0){const q=l()[E-1];A(q),q.focus()}H()}else k.key==="ArrowLeft"&&E>0?(k.preventDefault(),(I=l()[E-1])==null||I.focus()):k.key==="ArrowRight"&&E<5?(k.preventDefault(),(U=l()[E+1])==null||U.focus()):k.key==="Escape"&&r()}),S.addEventListener("paste",k=>{var q,J;k.preventDefault();const I=(((q=k.clipboardData)==null?void 0:q.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const U=l();I.split("").forEach((z,Y)=>{U[Y]&&b(U[Y],z)}),(J=U[Math.min(I.length-1,5)])==null||J.focus(),V(),H(),C().length===6&&setTimeout($,80)}),S.addEventListener("focus",()=>S.select())});const M=s.querySelector("#__crossx-pin6-numpad");if(M){let S=null;const E=()=>{S&&(S.classList.remove("--pressed"),S=null)};M.addEventListener("pointerdown",I=>{const U=I.target.closest(".__crossx-pin6-numpad-key");!U||a||c||(E(),S=U,U.classList.add("--pressed"),U.setPointerCapture(I.pointerId))});const k=I=>{const U=I.dataset.key;if(!U)return;if(U==="backspace"){const Y=[...l()].reverse().find(We=>R(We));Y&&(A(Y),V()),H();return}if(!/^\d$/.test(U))return;const J=l().find(z=>!R(z));J&&(b(J,U),V(),H(),C().length===6&&setTimeout($,80))};M.addEventListener("pointerup",I=>{if(!S)return;const U=S;E();const q=U.getBoundingClientRect();I.clientX>=q.left&&I.clientX<=q.right&&I.clientY>=q.top&&I.clientY<=q.bottom&&!a&&!c&&k(U)}),M.addEventListener("pointercancel",E),M.addEventListener("pointerleave",E,!0),H(),i&&i>Date.now()&&K()}}const uc=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3055
3055
  <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"/>
3056
3056
  <line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3057
3057
  <line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3058
- </svg>`,dn=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3058
+ </svg>`,un=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3059
3059
  <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"/>
3060
- </svg>`,cc=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3060
+ </svg>`,hc=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3061
3061
  <path d="M1 4.5L4 7.5L10 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
3062
- </svg>`,lc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3062
+ </svg>`,pc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3063
3063
  <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"/>
3064
- </svg>`;function dc(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var h;c.preventDefault();const l=(((h=c.clipboardData)==null?void 0:h.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,f)=>{t[f]&&(t[f].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class uc{constructor(e="light",r,t=kt,n){this.theme=e,this.overrides=r,this.tokens=Ys(e,r),this.displayDecimals=t,this.pinKeyboard=n,ga()}setPinKeyboard(e){this.pinKeyboard=e}resolvePinKeyboardMode(){const e=this.pinKeyboard;if(typeof e=="function")try{return e()==="native"?"native":"virtual"}catch{return"virtual"}return e==="native"?"native":"virtual"}applyPinKeyboardMode(e){e&&e.classList.toggle("--native-keypad",this.resolvePinKeyboardMode()==="native")}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=Ys(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((n,i)=>{var R;de();const o=[...e],a=Va(o,this.tokens,t,this.messages),c=$e();ue(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())};let h=null;const _=k=>{u(),n(k)},f=()=>{u(),h?i(h):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(k=>{k.addEventListener("click",()=>{const L=k.dataset.walletAddress??"",U=parseInt(k.dataset.walletIndex??"0",10),G=o.find(ae=>ae.index===U);_({address:L,index:U,name:G==null?void 0:G.name})})})})();const w=a.querySelector("#__crossx-add-wallet-error"),b=a.querySelector("#__crossx-add-wallet-btn");b&&b.addEventListener("click",async()=>{b.disabled=!0,w&&(w.hidden=!0,w.textContent="");try{const k=await r();o.push(k);const L=a.querySelector("#__crossx-wallet-list");if(L){const U=document.createElement("button");U.className="__crossx-wallet-item",U.dataset.walletIndex=String(k.index),U.dataset.walletAddress=k.address,U.innerHTML=`${cn(k.address,k.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(an(k))}</span><span class="__crossx-wallet-addr">${Xs(k.address)}</span></span>`,U.addEventListener("click",()=>_(k)),L.appendChild(U);try{U.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}b.disabled=!1}catch(k){const L=k instanceof g&&k.code===p.ADDRESS_LIMIT_EXCEEDED,U=this.resolveAddWalletErrorMessage(k);w&&(w.textContent=U,w.hidden=!1),L?(b.disabled=!0,b.setAttribute("aria-disabled","true")):b.disabled=!1,h=k}}),(R=a.querySelector("#__crossx-close-btn"))==null||R.addEventListener("click",f),a.addEventListener("click",k=>{k.target===a&&f()});const A=k=>{k.key==="Escape"&&(document.removeEventListener("keydown",A),f())};document.addEventListener("keydown",A)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,c;de();const r=za(this.tokens,this.messages),t=$e();ue(r);let n=!1,i=null;const o=()=>{n||(n=!0,i&&document.removeEventListener("keydown",i),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",o),(c=r.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),r.addEventListener("click",l=>{l.target===r&&o()}),i=l=>{l.key==="Escape"&&o()},document.addEventListener("keydown",i)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof g&&e.code===p.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:ot;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(Ue).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var _,f,x,w;de();const i=Za(this.tokens,r,this.messages),o=$e();ue(i);const a=()=>{i.remove(),o()},c=b=>{a(),n({type:"oauth",provider:b})},l=b=>{a(),n({type:"external",walletId:b})},u=()=>{a(),n(null)};(_=i.querySelector("#__crossx-apple-btn"))==null||_.addEventListener("click",()=>c("apple")),(f=i.querySelector("#__crossx-google-btn"))==null||f.addEventListener("click",()=>c("google")),(x=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||x.addEventListener("click",b=>{const R=b.currentTarget.dataset.walletId??"";R&&l(R)}),(w=i.querySelector("#__crossx-close-btn"))==null||w.addEventListener("click",u),i.addEventListener("click",b=>{b.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(b=>{b.addEventListener("click",A=>A.stopPropagation())});const h=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)})}showSessionAlert(e){return new Promise(r=>{var u,h,_;de();const t=this.messages,n=Qa(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.session_alert_account_label)??"Account",signOutLabel:(t==null?void 0:t.session_alert_sign_out_button)??"Sign out",signInAgainLabel:(t==null?void 0:t.session_alert_sign_in_again_button)??"Sign in again"}),i=$e();ue(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(h=n.querySelector("#__crossx-session-signin"))==null||h.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;de();const n=ec(this.tokens,r);ue(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const h=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)}})}showPinSetupPrompt(e){return new Promise(r=>{de();const t=this.messages,n={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pin_notice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},i={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pin_setup_mismatch_error)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Confirm your 6-digit PIN"},a=ln(this.tokens,nc(n)),c=$e();ue(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},h=R=>{u(),r(R)},_=()=>{u(),r(null)},f=a.querySelector(".__crossx-card"),x={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},w=R=>{var k;f.innerHTML=gr({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(f),(k=f.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",_),xr(f,L=>{L===R?h(R):b(i.mismatchError)},_)},b=R=>{var k;f.innerHTML=gr({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:R}),this.applyPinKeyboardMode(f),(k=f.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",_),xr(f,L=>{const U=ic(L,x);U?b(U):w(L)},_)};(()=>{var V;const R=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),k=f.querySelector("#__crossx-pin-notice-next"),L=new Set;k.removeAttribute("disabled");const U=k.dataset.nextLabel??"Next",G=k.dataset.submitLabel??"I Understand",ae=()=>{const K=L.size===R.length;k.classList.toggle("--disabled",!K),k.textContent=G||U},Y=(K,B)=>{if(L.has(B))return;const F=K.querySelector(`#__crossx-notice-check-${B}`);L.add(B),F.classList.add("--checked"),K.setAttribute("aria-checked","true"),ae()},X=(K,B)=>{if(!L.has(B))return;const F=K.querySelector(`#__crossx-notice-check-${B}`);L.delete(B),F.classList.remove("--checked"),K.setAttribute("aria-checked","false"),ae()};R.forEach(K=>{const B=parseInt(K.dataset.checkIndex??"0",10);K.addEventListener("click",()=>{L.has(B)?X(K,B):Y(K,B)}),K.addEventListener("keydown",F=>{(F.key===" "||F.key==="Enter")&&(F.preventDefault(),L.has(B)?X(K,B):Y(K,B))})}),k.addEventListener("click",()=>{if(L.size===R.length){b(e==null?void 0:e.errorMessage);return}const K=R.find(F=>{const m=parseInt(F.dataset.checkIndex??"0",10);return!L.has(m)});if(!K)return;const B=parseInt(K.dataset.checkIndex??"0",10);K.scrollIntoView({behavior:"smooth",block:"nearest"}),K.classList.add("--highlight"),setTimeout(()=>{K.classList.remove("--highlight"),Y(K,B)},400)}),(V=f.querySelector("#__crossx-close-btn"))==null||V.addEventListener("click",_)})(),a.addEventListener("click",R=>{R.target===a&&_()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var A;de();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verify_pin_title)??"Verify Your PIN":(n==null?void 0:n.pin_input_title)??"Enter PIN",a=i?(n==null?void 0:n.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pin_locked_failure_warning)??"Your account will be locked after further failures.",l=ln(this.tokens,gr({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=$e();ue(l);let h=!1;const _=()=>{h||(h=!0,l.remove(),u())},f=R=>{_(),r(R)},x=()=>{_(),r(null)},w=R=>{_(),t(R)},b=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(b),(A=b.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",x),xr(b,f,x,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;de();const t=tc(this.tokens,e);ue(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),dc(t,i,o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.addEventListener("click",l=>{l.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;de();const{overlay:n,startCountdown:i}=sc(this.tokens,e,r);ue(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;de();const t=Ba(e,this.tokens,this.messages);ue(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const h=l.dataset.copy;h&&((_=navigator.clipboard)==null||_.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{de();const n=Ma(e,this.tokens,this.messages);ue(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,h;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||($a(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,u,h;de();let t;e.type==="sign-message"?t=Fa(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Wa(e,this.tokens,this.messages):e.type==="sign"?t=Ta(e,this.tokens,this.displayDecimals,this.messages):t=Ca(e,this.tokens,this.displayDecimals,this.messages);const n=$e();ue(t);const i=()=>{t.remove(),n()},o=()=>{i(),r(!0)},a=()=>{i(),r(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(h=t.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",f=>{var w;f.stopPropagation();const x=_.dataset.copy;x&&((w=navigator.clipboard)==null||w.writeText(x).catch(()=>{}))})}),fa(t),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class hc{constructor(e,r,t,n=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=n}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:n,chainId:i}=this.mapToNativeParams(e),o={operation:t,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await r.requestUserConfirmation(o)}mapToNativeParams(e){const r=e.type;switch(r){case"sign-message":{const t=e;return{operation:"signMessage",payload:{message:t.message,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign-typed-data":{const t=e;return{operation:"signTypedData",payload:{typedData:t.typedData,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign":{const t=e;return{operation:"signTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"send":{const t=e;return{operation:"sendTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}default:throw new g(p.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t){const n=this.getBridge();if(this.shouldDelegateToBridge()&&(n!=null&&n.showWalletSelector))try{const i=await n.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===i.address.toLowerCase());return{address:i.address,index:(o==null?void 0:o.index)??i.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t)}async showWalletCreatedPrompt(){var e,r;if(!this.shouldDelegateToBridge())return((r=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:r.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,r){return this.browserConfirmation.setTheme(e,r)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var r,t;(t=(r=this.browserConfirmation).setPinKeyboard)==null||t.call(r,e)}}class un{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 pc(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3064
+ </svg>`;function fc(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var h;c.preventDefault();const l=(((h=c.clipboardData)==null?void 0:h.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,f)=>{t[f]&&(t[f].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class _c{constructor(e="light",r,t=kt,n){this.theme=e,this.overrides=r,this.tokens=Xs(e,r),this.displayDecimals=t,this.pinKeyboard=n,ya()}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=Xs(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((n,i)=>{var R;de();const o=[...e],a=Ya(o,this.tokens,t,this.messages),c=$e();ue(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())};let h=null;const _=C=>{u(),n(C)},f=()=>{u(),h?i(h):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(C=>{C.addEventListener("click",()=>{const D=C.dataset.walletAddress??"",H=parseInt(C.dataset.walletIndex??"0",10),K=o.find(re=>re.index===H);_({address:D,index:H,name:K==null?void 0:K.name})})})})();const w=a.querySelector("#__crossx-add-wallet-error"),b=a.querySelector("#__crossx-add-wallet-btn");b&&b.addEventListener("click",async()=>{b.disabled=!0,w&&(w.hidden=!0,w.textContent="");try{const C=await r();o.push(C);const D=a.querySelector("#__crossx-wallet-list");if(D){const H=document.createElement("button");H.className="__crossx-wallet-item",H.dataset.walletIndex=String(C.index),H.dataset.walletAddress=C.address,H.innerHTML=`${ln(C.address,C.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(cn(C))}</span><span class="__crossx-wallet-addr">${Zs(C.address)}</span></span>`,H.addEventListener("click",()=>_(C)),D.appendChild(H);try{H.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}b.disabled=!1}catch(C){const D=C instanceof g&&C.code===p.ADDRESS_LIMIT_EXCEEDED,H=this.resolveAddWalletErrorMessage(C);w&&(w.textContent=H,w.hidden=!1),D?(b.disabled=!0,b.setAttribute("aria-disabled","true")):b.disabled=!1,h=C}}),(R=a.querySelector("#__crossx-close-btn"))==null||R.addEventListener("click",f),a.addEventListener("click",C=>{C.target===a&&f()});const A=C=>{C.key==="Escape"&&(document.removeEventListener("keydown",A),f())};document.addEventListener("keydown",A)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,c;de();const r=Xa(this.tokens,this.messages),t=$e();ue(r);let n=!1,i=null;const o=()=>{n||(n=!0,i&&document.removeEventListener("keydown",i),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",o),(c=r.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),r.addEventListener("click",l=>{l.target===r&&o()}),i=l=>{l.key==="Escape"&&o()},document.addEventListener("keydown",i)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof g&&e.code===p.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:ot;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(Ue).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var _,f,x,w;de();const i=rc(this.tokens,r,this.messages),o=$e();ue(i);const a=()=>{i.remove(),o()},c=b=>{a(),n({type:"oauth",provider:b})},l=b=>{a(),n({type:"external",walletId:b})},u=()=>{a(),n(null)};(_=i.querySelector("#__crossx-apple-btn"))==null||_.addEventListener("click",()=>c("apple")),(f=i.querySelector("#__crossx-google-btn"))==null||f.addEventListener("click",()=>c("google")),(x=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||x.addEventListener("click",b=>{const R=b.currentTarget.dataset.walletId??"";R&&l(R)}),(w=i.querySelector("#__crossx-close-btn"))==null||w.addEventListener("click",u),i.addEventListener("click",b=>{b.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(b=>{b.addEventListener("click",A=>A.stopPropagation())});const h=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)})}showSessionAlert(e){return new Promise(r=>{var u,h,_;de();const t=this.messages,n=sc(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.session_alert_account_label)??"Account",signOutLabel:(t==null?void 0:t.session_alert_sign_out_button)??"Sign out",signInAgainLabel:(t==null?void 0:t.session_alert_sign_in_again_button)??"Sign in again"}),i=$e();ue(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(h=n.querySelector("#__crossx-session-signin"))==null||h.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;de();const n=nc(this.tokens,r);ue(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const h=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)}})}showPinSetupPrompt(e){return new Promise(r=>{de();const t=this.messages,n={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pin_notice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},i={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pin_setup_mismatch_error)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Confirm your 6-digit PIN"},a=dn(this.tokens,cc(n)),c=$e();ue(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},h=R=>{u(),r(R)},_=()=>{u(),r(null)},f=a.querySelector(".__crossx-card"),x={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},w=R=>{var C;f.innerHTML=xr({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(f),(C=f.querySelector("#__crossx-close-btn"))==null||C.addEventListener("click",_),wr(f,D=>{D===R?h(R):b(i.mismatchError)},_)},b=R=>{var C;f.innerHTML=xr({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:R}),this.applyPinKeyboardMode(f),(C=f.querySelector("#__crossx-close-btn"))==null||C.addEventListener("click",_),wr(f,D=>{const H=lc(D,x);H?b(H):w(D)},_)};(()=>{var oe;const R=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),C=f.querySelector("#__crossx-pin-notice-next"),D=new Set;C.removeAttribute("disabled");const H=C.dataset.nextLabel??"Next",K=C.dataset.submitLabel??"I Understand",re=()=>{const L=D.size===R.length;C.classList.toggle("--disabled",!L),C.textContent=K||H},ie=(L,F)=>{if(D.has(F))return;const W=L.querySelector(`#__crossx-notice-check-${F}`);D.add(F),W.classList.add("--checked"),L.setAttribute("aria-checked","true"),re()},V=(L,F)=>{if(!D.has(F))return;const W=L.querySelector(`#__crossx-notice-check-${F}`);D.delete(F),W.classList.remove("--checked"),L.setAttribute("aria-checked","false"),re()};R.forEach(L=>{const F=parseInt(L.dataset.checkIndex??"0",10);L.addEventListener("click",()=>{D.has(F)?V(L,F):ie(L,F)}),L.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),D.has(F)?V(L,F):ie(L,F))})}),C.addEventListener("click",()=>{if(D.size===R.length){b(e==null?void 0:e.errorMessage);return}const L=R.find(W=>{const m=parseInt(W.dataset.checkIndex??"0",10);return!D.has(m)});if(!L)return;const F=parseInt(L.dataset.checkIndex??"0",10);L.scrollIntoView({behavior:"smooth",block:"nearest"}),L.classList.add("--highlight"),setTimeout(()=>{L.classList.remove("--highlight"),ie(L,F)},400)}),(oe=f.querySelector("#__crossx-close-btn"))==null||oe.addEventListener("click",_)})(),a.addEventListener("click",R=>{R.target===a&&_()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var A;de();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verify_pin_title)??"Verify Your PIN":(n==null?void 0:n.pin_input_title)??"Enter PIN",a=i?(n==null?void 0:n.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pin_locked_failure_warning)??"Your account will be locked after further failures.",l=dn(this.tokens,xr({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=$e();ue(l);let h=!1;const _=()=>{h||(h=!0,l.remove(),u())},f=R=>{_(),r(R)},x=()=>{_(),r(null)},w=R=>{_(),t(R)},b=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(b),(A=b.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",x),wr(b,f,x,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;de();const t=ic(this.tokens,e);ue(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),fc(t,i,o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.addEventListener("click",l=>{l.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;de();const{overlay:n,startCountdown:i}=ac(this.tokens,e,r);ue(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;de();const t=Wa(e,this.tokens,this.messages);ue(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const h=l.dataset.copy;h&&((_=navigator.clipboard)==null||_.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{de();const n=Ua(e,this.tokens,this.messages);ue(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,h;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(Ha(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,u,h;de();let t;e.type==="sign-message"?t=Ga(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=Ka(e,this.tokens,this.messages):e.type==="sign"?t=Na(e,this.tokens,this.displayDecimals,this.messages):t=La(e,this.tokens,this.displayDecimals,this.messages);const n=$e();ue(t);const i=()=>{t.remove(),n()},o=()=>{i(),r(!0)},a=()=>{i(),r(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(h=t.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",f=>{var w;f.stopPropagation();const x=_.dataset.copy;x&&((w=navigator.clipboard)==null||w.writeText(x).catch(()=>{}))})}),wa(t),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class gc{constructor(e,r,t,n=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=n}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:n,chainId:i}=this.mapToNativeParams(e),o={operation:t,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await r.requestUserConfirmation(o)}mapToNativeParams(e){const r=e.type;switch(r){case"sign-message":{const t=e;return{operation:"signMessage",payload:{message:t.message,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign-typed-data":{const t=e;return{operation:"signTypedData",payload:{typedData:t.typedData,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign":{const t=e;return{operation:"signTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"send":{const t=e;return{operation:"sendTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}default:throw new g(p.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t){const n=this.getBridge();if(this.shouldDelegateToBridge()&&(n!=null&&n.showWalletSelector))try{const i=await n.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===i.address.toLowerCase());return{address:i.address,index:(o==null?void 0:o.index)??i.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t)}async showWalletCreatedPrompt(){var e,r;if(!this.shouldDelegateToBridge())return((r=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:r.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,r){return this.browserConfirmation.setTheme(e,r)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var r,t;(t=(r=this.browserConfirmation).setPinKeyboard)==null||t.call(r,e)}}class hn{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 xc(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3065
3065
  Set the projectId field in SDKConfig when calling createCROSSxSDK().
3066
- Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=He.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&Or.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Or(s.projectId):new Qn,a=new jo,c=new Qo,l=new Be,u=new un,h=new Pt;let _;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new ca(o,h)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Me(n,o,c,u,h));let f=null;const x=()=>{var G;return((G=f==null?void 0:f.isAuthenticatedViaRNBridge)==null?void 0:G.call(f))??!1},w=()=>{var G;return(G=f==null?void 0:f.assertRNBridgeSessionActive)==null?void 0:G.call(f)};_=new la(_,()=>{var G;return(G=f==null?void 0:f.getRNBridge)==null?void 0:G.call(f)},x,w,()=>s.appName);const b=new it(n,c),A=new uc(s.theme??"light",s.themeTokens,s.displayDecimals,s.pinKeyboard),R=new hc(A,()=>{var G;return(G=f==null?void 0:f.getRNBridge)==null?void 0:G.call(f)},()=>typeof window<"u"?window.location.origin:"http://localhost",x),k=e!=null&&e.wrapConfirmation?e.wrapConfirmation(R):R,L=new ut(t,n,o,a,c,l,_,u,k,b,h);f=L;const U=L.signInUseCase;return U&&typeof U.setFreshTokenCallback=="function"&&U.setFreshTokenCallback(()=>L.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=L),L}function fc(s){const e=_c(s),r=gc(e),t=JSON.parse(r);wc(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function _c(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function gc(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=xc(s);return decodeURIComponent(e)}function xc(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function wc(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return j.CONNECT_OTHER_WALLET_DISPLAY_ORDER=vr,j.CROSSxError=g,j.CROSSxEthereumProvider=Ar,j.CROSSxSDK=ut,j.ChainId=vn,j.ConnectOtherWalletItem=Ue,j.ErrorCode=p,j.MNEMONIC_ADDRESS_LIMIT=ot,j.PinMemoryStore=Pt,j.TokenMemoryStore=un,j.WALLET_BRAND_NAME=at,j.createCROSSxSDK=pc,j.getConnectOtherWalletLabel=Er,j.getWalletBrowserInfo=st,j.isWalletInAppBrowser=na,j.parseOAuthDeeplink=fc,j.waitForWalletBrowser=ia,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"}),j}({});
3066
+ Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=He.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,legacyOauthServiceUrl:r.legacyOauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&Lr.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Lr(s.projectId):new ei,a=new Yo,c=new ea,l=new Be,u=new hn,h=new Ot;let _;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new ha(o,h)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Me(n,o,c,u,h));let f=null;const x=()=>{var K;return((K=f==null?void 0:f.isAuthenticatedViaRNBridge)==null?void 0:K.call(f))??!1},w=()=>{var K;return(K=f==null?void 0:f.assertRNBridgeSessionActive)==null?void 0:K.call(f)};_=new pa(_,()=>{var K;return(K=f==null?void 0:f.getRNBridge)==null?void 0:K.call(f)},x,w,()=>s.appName);const b=new it(n,c),A=new _c(s.theme??"light",s.themeTokens,s.displayDecimals,s.pinKeyboard),R=new gc(A,()=>{var K;return(K=f==null?void 0:f.getRNBridge)==null?void 0:K.call(f)},()=>typeof window<"u"?window.location.origin:"http://localhost",x),C=e!=null&&e.wrapConfirmation?e.wrapConfirmation(R):R,D=new ut(t,n,o,a,c,l,_,u,C,b,h);f=D;const H=D.signInUseCase;return H&&typeof H.setFreshTokenCallback=="function"&&H.setFreshTokenCallback(()=>D.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=D),D}function wc(s){const e=mc(s),r=yc(e),t=JSON.parse(r);Sc(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function mc(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function yc(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=bc(s);return decodeURIComponent(e)}function bc(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Sc(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return j.CONNECT_OTHER_WALLET_DISPLAY_ORDER=Er,j.CROSSxError=g,j.CROSSxEthereumProvider=Ir,j.CROSSxSDK=ut,j.ChainId=En,j.ConnectOtherWalletItem=Ue,j.ErrorCode=p,j.MNEMONIC_ADDRESS_LIMIT=ot,j.PinMemoryStore=Ot,j.TokenMemoryStore=hn,j.WALLET_BRAND_NAME=at,j.createCROSSxSDK=xc,j.getConnectOtherWalletLabel=Ar,j.getWalletBrowserInfo=st,j.isWalletInAppBrowser=oa,j.parseOAuthDeeplink=wc,j.waitForWalletBrowser=aa,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"}),j}({});