@nexus-cross/crossx-sdk-core 2.6.0-beta.1 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/adapters/confirmation/HeadlessConfirmationAdapter.d.ts +25 -0
  2. package/dist/adapters/onewallet/AuthzKeyManager.d.ts +27 -0
  3. package/dist/adapters/onewallet/OneWalletApiAdapter.d.ts +61 -0
  4. package/dist/adapters/onewallet/OneWalletApiClient.d.ts +37 -0
  5. package/dist/adapters/onewallet/crypto/bytes.d.ts +16 -0
  6. package/dist/adapters/onewallet/crypto/envelope.d.ts +103 -0
  7. package/dist/adapters/onewallet/crypto/hpke.d.ts +17 -0
  8. package/dist/adapters/transport/SdkVersionTransport.d.ts +5 -1
  9. package/dist/core/config/environments.d.ts +5 -0
  10. package/dist/core/constants.d.ts +8 -6
  11. package/dist/core/ports/ConfirmationPort.d.ts +28 -1
  12. package/dist/core/services/PinMemoryStore.d.ts +4 -0
  13. package/dist/core/services/PinReusePolicy.d.ts +30 -0
  14. package/dist/core/types/errors.d.ts +2 -0
  15. package/dist/core/types/index.d.ts +14 -3
  16. package/dist/core/types/internal.d.ts +6 -0
  17. package/dist/core/usecases/SignOutUseCase.d.ts +2 -0
  18. package/dist/crossx.global +5 -3261
  19. package/dist/factory--q6B2KiB.js +7803 -0
  20. package/dist/factory-DKz-M7y8.cjs +9 -0
  21. package/dist/index.cjs +1 -1
  22. package/dist/index.d.ts +4 -2
  23. package/dist/index.js +19 -16
  24. package/dist/internal.cjs +1 -1
  25. package/dist/internal.d.ts +2 -0
  26. package/dist/internal.js +4 -3
  27. package/dist/sdk/CROSSxSDK.d.ts +13 -0
  28. package/dist/sdk/factory.d.ts +18 -3
  29. package/dist/sdk/services/AddressResolverService.d.ts +2 -0
  30. package/dist/sdk/services/OneIdSessionManager.d.ts +2 -0
  31. package/dist/sdk/services/PinOrchestrator.d.ts +12 -0
  32. package/dist/sdk/services/SigningOrchestrator.d.ts +3 -0
  33. package/package.json +1 -1
  34. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +0 -140
  35. package/dist/adapters/confirmation/walletCreatedIllustration.d.ts +0 -11
  36. package/dist/factory-ATsDw5Ju.js +0 -11700
  37. package/dist/factory-WRv_65Rh.cjs +0 -3265
@@ -1,3265 +1,9 @@
1
- var CROSSx=(function(X){"use strict";var $l=Object.defineProperty;var Ul=(X,h,_)=>h in X?$l(X,h,{enumerable:!0,configurable:!0,writable:!0,value:_}):X[h]=_;var P=(X,h,_)=>Ul(X,typeof h!="symbol"?h+"":h,_);var Mt,Fn;var h=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.ONEID_TERMS_NOT_AGREED="ONEID_TERMS_NOT_AGREED",s.ONEID_ACCOUNT_NOT_FOUND="ONEID_ACCOUNT_NOT_FOUND",s.ONEID_SERVICE_NOT_LINKED="ONEID_SERVICE_NOT_LINKED",s.ONEID_AUTHORIZATION_FAILED="ONEID_AUTHORIZATION_FAILED",s.ONEID_STATE_MISMATCH="ONEID_STATE_MISMATCH",s.ONEID_ISSUER_MISMATCH="ONEID_ISSUER_MISMATCH",s.ONEID_TIMEOUT="ONEID_TIMEOUT",s.ONEID_SESSION_EVICTED="ONEID_SESSION_EVICTED",s.ONEID_SESSION_REVOKED="ONEID_SESSION_REVOKED",s.ONEID_SESSION_EXPIRED="ONEID_SESSION_EXPIRED",s.ONEID_SESSION_INVALID="ONEID_SESSION_INVALID",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SDK_VERSION_UNSUPPORTED="SDK_VERSION_UNSUPPORTED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.EXECUTION_REVERTED="EXECUTION_REVERTED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",s.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",s.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(h||{});class _ extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Hn=2e3,Or=6e4,Gn=1e3,Kn=1e4,Vn="0x77359400",kr="0x3B9ACA00",Pr=130,$t=6,Dr=18,Lr=3e4,qn=300*1e3,zn=30*1e3,dt=100,Jn=300*1e3,Br=60*1e3,ut="crossx-sdk-js/2.6.0-beta.1",jn="X-SDK-Version",Yn=!1,Xn="x-sdk-deprecation",ht=-10050,pt="ONEpocket";var We=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(We||{});const Zn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:pt},Mr=["crossx","io.metamask","com.binance.wallet"];function $r(s){return Zn[s]??s}function Qn(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...Mr]:[]}function Ur(s){const e=s instanceof Error?s.message:String(s);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const ei=new Set(["ERR_USER_REJECTED","USER_REJECTED","USER_REJECT"]),ti=/user rejected|rejected the request|request (?:was )?cancell?ed|entry was cancell?ed|거부했습니다|취소되었습니다/i;function Fr(s){if(!s||typeof s!="object")return;const e=s.code;return typeof e=="string"&&e.length>0?e:void 0}function ri(s){const e=Fr(s);if(e)return ei.has(e);const r=s instanceof Error?s.message:String(s);return ti.test(r)}function He(s,e){if(s instanceof _)return s;const r=Fr(s),t=s instanceof Error?s.message:String(s),n={nativeCode:r,cause:s};if(ri(s))return new _(h.USER_REJECTED,t,n);const i=r&&!t.includes(r)?`${t} (${r})`:t;return new _(e,i,n)}const _t={ONE_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"ONEchain Mainnet",nativeCurrency:{symbol:"ONE",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},ONE_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},si=Object.fromEntries(Object.entries(_t).map(([s,e])=>[s,e.caipId])),ni=new Map(Object.values(_t).map(s=>[s.caipId,s]));new Map(Object.values(_t).map(s=>[s.chainId,s]));const ii={symbol:"",decimals:18};function oi(s,e){var r;return(e==null?void 0:e[s])??((r=ni.get(s))==null?void 0:r.nativeCurrency)}class Ut{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new _(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new _(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let ye=null;function Fl(s){}function Wr(s){ye=s}const u={info(...s){if(ye){ye.log(...s);return}console.log(...s)},log(...s){if(ye){ye.log(...s);return}},warn(...s){if(ye){ye.warn(...s);return}},error(...s){if(ye){ye.error(...s);return}}},ai={confirm:"확인",cancel:"취소",close:"닫기",signature_requesting:"이(가) 서명을 요청합니다",signature_warning:"서명 후에는 변경하거나 취소할 수 없습니다.",signature_sign_button:"서명",sign_message_title:"서명 요청",sign_typed_data_title:"서명 요청",sign_transaction_title:"서명 요청",send_transaction_title:"트랜잭션 승인",send_tx_permission_text:"이(가) 다음 트랜잭션 승인을 요청합니다.",send_tx_approve_button:"승인",send_tx_confirm_button:"확인",tx_pending:"트랜잭션을 처리하고 있습니다...",tx_success:"트랜잭션 완료",tx_failed:"트랜잭션 실패",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",tx_progress_waiting_title:"확인 대기 중",tx_progress_waiting_text:"트랜잭션 영수증을 기다리는 중...",tx_complete_done_button:"모두 완료",label_to:"받는 주소",label_from:"보내는 주소",label_network:"네트워크",label_value:"금액",label_estimated_fee:"예상 수수료",label_est_tx_fee:"예상 수수료",label_max_priority_fee:"최대 우선 수수료",label_max_gas_fee:"최대 가스 수수료",label_gas_price:"가스 가격",label_gas_limit:"가스 한도",label_transfer:"전송량",label_tx_fee:"수수료",label_tx_hash:"Tx 해시",label_total:"합계",label_including_fees:"(수수료 포함)",label_primary_type:"Primary Type",login_selector_title:"로그인 방법 선택",login_selector_subtitle:"소셜 계정으로 간편하게 로그인하세요",login_selector_google:"Google로 로그인",login_selector_apple:"Apple로 로그인",login_selector_or:"또는",login_selector_terms_template:"계속 진행하면 NEXUS {tos}에 동의하고 {pp}에 동의하게 됩니다.",login_selector_terms_tos:"이용약관",login_selector_terms_pp:"개인정보 처리방침",login_selector_connect_other_wallets:"다른 지갑으로 연결",login_selector_connect_other_wallets_desc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_found_title:"소셜 계정에서 지갑 발견",migration_found_description:`소셜 계정에 연결된 지갑을 발견했습니다.
1
+ var CROSSx=(function(W){"use strict";var ll=Object.defineProperty;var dl=(W,l,h)=>l in W?ll(W,l,{enumerable:!0,configurable:!0,writable:!0,value:h}):W[l]=h;var T=(W,l,h)=>dl(W,typeof l!="symbol"?l+"":l,h);var Ct,xn;var l=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.ONEID_TERMS_NOT_AGREED="ONEID_TERMS_NOT_AGREED",s.ONEID_ACCOUNT_NOT_FOUND="ONEID_ACCOUNT_NOT_FOUND",s.ONEID_SERVICE_NOT_LINKED="ONEID_SERVICE_NOT_LINKED",s.ONEID_AUTHORIZATION_FAILED="ONEID_AUTHORIZATION_FAILED",s.ONEID_STATE_MISMATCH="ONEID_STATE_MISMATCH",s.ONEID_ISSUER_MISMATCH="ONEID_ISSUER_MISMATCH",s.ONEID_TIMEOUT="ONEID_TIMEOUT",s.ONEID_SESSION_EVICTED="ONEID_SESSION_EVICTED",s.ONEID_SESSION_REVOKED="ONEID_SESSION_REVOKED",s.ONEID_SESSION_EXPIRED="ONEID_SESSION_EXPIRED",s.ONEID_SESSION_INVALID="ONEID_SESSION_INVALID",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SDK_VERSION_UNSUPPORTED="SDK_VERSION_UNSUPPORTED",s.UI_NOT_PROVIDED="UI_NOT_PROVIDED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.EXECUTION_REVERTED="EXECUTION_REVERTED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.PIN_ENCRYPTION_INVALID="PIN_ENCRYPTION_INVALID",s.PIN_POLICY_VIOLATION="PIN_POLICY_VIOLATION",s.PIN_ENCRYPTION_FAILED="PIN_ENCRYPTION_FAILED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(l||{});class h extends Error{constructor(e,t,r){super(t),this.code=e,this.details=r,this.name="CROSSxError",Object.setPrototypeOf(this,h.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Dn=2e3,Ir=6e4,kn=1e3,Ln=1e4,Un="0x77359400",Tr="0x3B9ACA00",Rr=130,Dt=6,Or=18,Nr=3e4,Wn=300*1e3,Bn=30*1e3,kt=100,Mn=300*1e3,Pr=60*1e3,ot="crossx-sdk-js/3.0.0-beta.1",Fn="X-SDK-Version",Kn=!1,Hn="x-sdk-deprecation",ct=-10050,Lt="ONEpocket";var br=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(br||{});const Gn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:Lt},xr=["crossx","io.metamask","com.binance.wallet"];function $n(s){return Gn[s]??s}function Vn(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...xr]:[]}function vr(s){const e=s instanceof Error?s.message:String(s);return e.includes("BRIDGE_NOT_AUTHORIZED")||e.includes("Bridge session not authenticated")}const Jn=new Set(["ERR_USER_REJECTED","USER_REJECTED","USER_REJECT"]),qn=/user rejected|rejected the request|request (?:was )?cancell?ed|entry was cancell?ed|거부했습니다|취소되었습니다/i;function Cr(s){if(!s||typeof s!="object")return;const e=s.code;return typeof e=="string"&&e.length>0?e:void 0}function Yn(s){const e=Cr(s);if(e)return Jn.has(e);const t=s instanceof Error?s.message:String(s);return qn.test(t)}function Ue(s,e){if(s instanceof h)return s;const t=Cr(s),r=s instanceof Error?s.message:String(s),n={nativeCode:t,cause:s};if(Yn(s))return new h(l.USER_REJECTED,r,n);const i=t&&!r.includes(t)?`${r} (${t})`:r;return new h(e,i,n)}const lt={ONE_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"ONEchain Mainnet",nativeCurrency:{symbol:"ONE",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},ONE_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"ONEchain Testnet",nativeCurrency:{symbol:"tONE",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},zn=Object.fromEntries(Object.entries(lt).map(([s,e])=>[s,e.caipId])),Xn=new Map(Object.values(lt).map(s=>[s.caipId,s]));new Map(Object.values(lt).map(s=>[s.chainId,s]));const jn={symbol:"",decimals:18};function Zn(s,e){var t;return(e==null?void 0:e[s])??((t=Xn.get(s))==null?void 0:t.nativeCurrency)}class Ut{constructor(e,t){this.sdk=e,this.chainId=t,this._listeners=new Map}async request({method:e,params:t=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const r=await this.sdk.getAddress();return r?[r.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const r=this._normalizeEIP1193Tx(t[0]);return(await this.sdk.signTransaction(this.chainId,r)).signedTx}case"eth_sendTransaction":{const r=this._normalizeEIP1193Tx(t[0]);return(await this.sdk.sendTransaction(this.chainId,r)).txHash}case"personal_sign":case"eth_sign":throw new h(l.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new h(l.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,t,this.chainId)}}on(e,t){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(t),this}removeListener(e,t){var r;return(r=this._listeners.get(e))==null||r.delete(t),this}emit(e,...t){var r;(r=this._listeners.get(e))==null||r.forEach(n=>n(...t))}_caip2ToHex(e){const t=e.split(":");return`0x${parseInt(t[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let pe=null;function hl(s){}function Dr(s){pe=s}const d={info(...s){if(pe){pe.log(...s);return}console.log(...s)},log(...s){if(pe){pe.log(...s);return}},warn(...s){if(pe){pe.warn(...s);return}},error(...s){if(pe){pe.error(...s);return}}},kr={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_empty:"아직 지갑이 없습니다. 지갑을 추가해 주세요.",wallet_selector_add_error_limit_exceeded:"계정 한도에 도달했습니다. 최대 {limit}개의 계정을 사용할 수 있습니다.",wallet_selector_add_error_generic:"새 계정을 추가하지 못했습니다. 다시 시도해 주세요.",wallet_created_title:"지갑이 생성되었습니다!",wallet_created_button:"확인",pin_notice_header_subtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pin_notice_title:"PIN 설정 주의사항",pin_notice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pin_notice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pin_notice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pin_notice_next_button:"확인했습니다",pin_notice_submit_button:"확인했습니다",pin_setup_title:"PIN 만들기",pin_setup_header_subtitle:"이 PIN은 거래 승인에 사용됩니다.",pin_setup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pin_setup_confirm_title:"PIN 확인",pin_setup_confirm_subtitle:"6자리 PIN을 다시 입력하세요.",pin_setup_mismatch_error:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pin_validation_too_short:"6자리 PIN을 입력해 주세요.",pin_validation_numbers_only:"숫자(0-9)만 입력할 수 있습니다.",pin_validation_repeating_digit:"동일한 숫자를 3회 이상 연속으로 사용할 수 없습니다.",pin_validation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pin_validation_alternating_pattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pin_input_title:"PIN 입력",pin_input_subtitle:"거래 승인을 위해 PIN을 입력해 주세요.",pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verify_pin_title:"PIN 확인",verify_pin_subtitle:"계속하려면 PIN을 확인해 주세요.",pin_locked_message:"잠금이 해제된 후 다시 시도해 주세요.",pin_locked_available_from:"(%@ 이후 이용 가능)",pin_locked_failure_warning:"추가 실패 시 계정이 잠금됩니다.",pin_locked_permanent:"계정이 영구 잠금되었습니다. 고객센터에 문의해 주세요.",alert_session_expired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_account_withdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_wallet_not_found:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_different_account:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
3
3
 
4
- 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,update_required_title:"업데이트 필요",update_required_message:"이 서비스가 더 이상 지원하지 않는 지갑 버전을 사용하고 있어 지금은 로그인하거나 전송할 수 없습니다. 서비스가 업데이트된 뒤 다시 시도해 주세요.",update_required_confirm_button:"확인",session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},Hr={confirm:"Confirm",cancel:"Cancel",close:"Close",signature_requesting:" is requesting a Signature",signature_warning:"After you sign, changes or cancellations are not possible.",signature_sign_button:"Sign",sign_message_title:"Sign Message",sign_typed_data_title:"Sign Data",sign_transaction_title:"Sign Transaction",send_transaction_title:"Send Transaction",send_tx_permission_text:" wants your permission to approve the following transaction.",send_tx_approve_button:"Approve",send_tx_confirm_button:"Confirm",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:pt,login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_empty:"No wallet yet. Add a wallet to continue.",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
4
+ 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,update_required_title:"업데이트 필요",update_required_message:"이 서비스가 더 이상 지원하지 않는 지갑 버전을 사용하고 있어 지금은 로그인하거나 전송할 수 없습니다. 서비스가 업데이트된 뒤 다시 시도해 주세요.",update_required_confirm_button:"확인",session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},Wt={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:Lt,login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Connected Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_empty:"No wallet yet. Add a wallet to continue.",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",wallet_created_title:"Wallet Created!",wallet_created_button:"Got it",pin_notice_header_subtitle:"Required for transactions, PK/mnemonic export & account deletion.",pin_notice_title:"PIN Setup Notice",pin_notice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pin_notice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pin_notice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pin_notice_next_button:"I Understand",pin_notice_submit_button:"I Understand",pin_setup_title:"Create PIN",pin_setup_header_subtitle:"This PIN is used to authorize your transactions.",pin_setup_subtitle:"Set a 6-digit PIN to authorize transactions.",pin_setup_confirm_title:"Confirm PIN",pin_setup_confirm_subtitle:"Confirm your 6-digit PIN",pin_setup_mismatch_error:"PINs do not match. Please try again.",pin_validation_too_short:"Please enter a 6-digit PIN.",pin_validation_numbers_only:"Only numbers (0-9) are allowed.",pin_validation_repeating_digit:"Cannot use the same number 3+ times in a row.",pin_validation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pin_validation_alternating_pattern:"Repeating patterns (e.g., 121212) are not allowed.",pin_input_title:"Enter PIN",pin_input_subtitle:"Enter your 6-digit PIN to continue.",pin_input_error:"Incorrect PIN. Please try again.",verify_pin_title:"Verify Your PIN",verify_pin_subtitle:"To continue, please confirm your PIN.",pin_locked_message:"Please try again after the lock expires.",pin_locked_available_from:"Available from",pin_locked_failure_warning:"Your account will be locked after further failures.",pin_locked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_session_expired:"Your session has expired. Please sign in again.",alert_account_withdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_wallet_not_found:"Wallet data could not be found. Please sign in again.",alert_different_account:`You signed in with a different Google/Apple account than before.
5
5
 
6
- For security, you must continue with the same account.`,update_required_title:"Update required",update_required_message:"This service is using a wallet version that is no longer supported, so you cannot sign in or send transactions right now. Please try again after the service is updated.",update_required_confirm_button:"OK",session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},ci={ko:ai,en:Hr};function be(s="en",e){return ci[s]??Hr}function li(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Gr="crossx_access_token",Kr="crossx_refresh_token",Vr="crossx_user_info",Bt=class Bt{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const d=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${d}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${d}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${d}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${d}_rn_bridge_session`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredAccessToken(){try{return!!await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN)}catch{return!1}}async hasStoredRNBridgeSession(){try{return await this.storage.get(this.STORAGE_KEY_RN_BRIDGE_SESSION)?!0:await this.hasStoredAccessToken()?!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN):!1}catch{return!1}}async clearStoredRNBridgeSession(){await this.storage.remove(this.STORAGE_KEY_RN_BRIDGE_SESSION)}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new _(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o,legacyOauthServiceUrl:a}=this.config,c=li(this.getLocale()),l=g=>{const w=`${g}${i}`,m=w.includes("?")?"&":"?";return`${w}${m}locale=${c}`},d=l(o),p=a?l(a):void 0;u.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),u.log(`[CROSSx] Auth URL: ${d}`);const f=await this.oauth.openAuth({authUrl:d,...p?{legacyAuthUrl:p}:{},expectedOrigin:new URL(o).origin});r=f.token,t=f.email,u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&u.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){if(u.error("[CROSSx] SignIn 에러 (OAuth 단계):",n),n instanceof _)throw n;const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new _(h.OAUTH_POPUP_BLOCKED,i):new _(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return u.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return u.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const d=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=d.firebase)==null?void 0:t.sign_in_provider);const p=((n=d.firebase)==null?void 0:n.identities)??{};c=d.email??((i=p.email)==null?void 0:i[0]),u.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{u.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const d=await this.crypto.verifyJWT(a);if(!d.valid)throw new _(h.AUTH_FAILED,"Access token 검증 실패");const p=d.payload;r={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),u.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),u.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new _(h.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return u.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return u.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:d}=this.config,{accessToken:p,refreshToken:f}=await this.exchangeFirebaseToken(e,d);let g,w,m;try{const S=this.crypto.decodeJWT(e);u.log("[CROSSx] Firebase JWT 필드:",Object.keys(S).join(", ")),w=(i=S.firebase)==null?void 0:i.sign_in_provider;const I=((o=S.firebase)==null?void 0:o.identities)??{};m=S.email??((a=I.email)==null?void 0:a[0]),w==="google.com"?g=(c=I["google.com"])==null?void 0:c[0]:w==="apple.com"&&(g=(l=I["apple.com"])==null?void 0:l[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",w,"hasProviderSub:",!!g,"email:",m??"(없음)")}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const S=this.crypto.decodeJWT(p);u.log("[CROSSx] access_token 디코딩 — sub:",S.sub,"exp:",S.exp,"필드:",Object.keys(S).join(", "));const I=await this.crypto.verifyJWT(p);if(n=I.signatureVerified??!1,!I.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const U=I.payload,C=U.email??m??r;u.log("[CROSSx] email 소스 — CROSSx JWT:",U.email??"(없음)","/ Firebase JWT:",m??"(없음)","/ OAuth 콜백:",r??"(없음)","→",C??"(없음)"),t={id:U.sub,email:C,signInProvider:w,providerSub:g},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),f&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,f):f&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const S=this.crypto.decodeJWT(e);t={id:S.sub,email:S.email??r,signInProvider:w,providerSub:g},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}u.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const x=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,x),await this.clearStoredRNBridgeSession(),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(d){return u.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",d),{success:!1,error:d instanceof Error?d.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;u.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){u.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new _(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}u.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new _(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return u.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return u.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return u.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;u.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof _&&e.code===h.SESSION_EXPIRED;return u.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const d=this.tokenStore.get()??"";d&&(i.access_token=d),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const d=Bt.REFRESH_RELOGIN_CODES.has(c.code);throw new _(d?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new _(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const d=this.extractRefreshToken(a);d&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,d)}return u.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){u.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),u.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof _&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(u.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(u.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof _&&e.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):u.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;u.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return u.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Vr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(Gr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Kr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Vr),await this.storage.remove(Gr),await this.storage.remove(Kr),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",i),i==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof _&&i.code===h.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof _&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED||i.code===h.SDK_VERSION_UNSUPPORTED))throw u.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};Bt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Ft=Bt;class di{constructor(e,r,t,n=[]){this.config=e,this.storage=r,this.tokenStore=t,this.preservedKeys=n;const i=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${i}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${i}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${i}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER);const e=[];for(const r of this.preservedKeys){const t=await this.storage.get(r).catch(()=>null);t!=null&&e.push([r,t])}await this.storage.clear();for(const[r,t]of e)await this.storage.set(r,t).catch(()=>{})}}class ui{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new _(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Wt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}const hi="/authorize/result",pi="one-oauth:authorization_response",qr="one-oauth:authorization_error",_i="one-oauth:authorization_ack",fi="openid profile offline_access";function Ht(s){let e="";for(const r of s)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function zr(s=32){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ht(e)}async function Jr(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Ht(new Uint8Array(e))}function ft(s=16){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ht(e)}const gi=300*1e3,xi=600*1e3,Gt="crossx.oneid.pending",wi=1e3,mi=10;function jr(s){switch(s){case"access_denied":return h.USER_REJECTED;case"required_items_not_agreed":return h.ONEID_TERMS_NOT_AGREED;case"account_not_found":return h.ONEID_ACCOUNT_NOT_FOUND;case"service_not_linked":return h.ONEID_SERVICE_NOT_LINKED;default:return h.ONEID_AUTHORIZATION_FAILED}}function yi(s){switch(s){case"session_evicted":return h.ONEID_SESSION_EVICTED;case"session_revoked":return h.ONEID_SESSION_REVOKED;case"session_expired":return h.ONEID_SESSION_EXPIRED;default:return h.ONEID_SESSION_INVALID}}function Kt(s){if(!(typeof s!="string"||!s.startsWith("/"))&&!(s.startsWith("//")||s.startsWith("/\\")))return s}function Ge(s){let e;try{e=new URL(s)}catch{throw new _(h.INVALID_CONFIG,"ONE ID issuer가 올바른 URL이 아닙니다")}return e.toString().replace(/\/+$/,"")}function Yr(s){const e=s.split(".")[1];if(!e)return null;try{const r=e.replace(/-/g,"+").replace(/_/g,"/"),t=r+"=".repeat((4-r.length%4)%4),n=new TextDecoder().decode(Uint8Array.from(atob(t),o=>o.charCodeAt(0))),i=JSON.parse(n);return typeof i=="object"&&i!==null?i:null}catch{return null}}function bi(s){if(typeof s!="object"||s===null)return!1;const e=s.type;return e===pi||e===qr}function Xr(s,e){if(typeof s.access_token!="string"||s.access_token==="")throw new _(h.ONEID_AUTHORIZATION_FAILED,"토큰 응답에 access_token이 없습니다");const r=typeof s.expires_in=="number"?s.expires_in:0;return{accessToken:s.access_token,tokenType:typeof s.token_type=="string"?s.token_type:"Bearer",expiresAt:e+r*1e3,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:void 0,idToken:typeof s.id_token=="string"?s.id_token:void 0,scope:typeof s.scope=="string"?s.scope:void 0}}class Si{constructor(){this.reason=null,this.onAbort=null}abort(e){var r;this.reason??(this.reason=e),(r=this.onAbort)==null||r.call(this,e)}throwIfAborted(){if(this.reason!==null)throw new _(h.USER_REJECTED,this.reason)}}class vi{constructor(e={}){this.abortPending=null,this.popupSeq=0,this.options=e}get fetchImpl(){return this.options.fetch??((e,r)=>fetch(e,r))}now(){var e,r;return((r=(e=this.options).now)==null?void 0:r.call(e))??Date.now()}get pendingStorage(){return this.options.pendingStorage??window.sessionStorage}cancelPending(e="ONE ID 로그인 대기를 중단했습니다"){var r;(r=this.abortPending)==null||r.call(this,e)}async authorize(e){let r=null;if(e.mode!=="redirect"&&(r=this.openBlankPopup(e.width,e.height),!r&&e.mode==="popup"))throw new _(h.OAUTH_POPUP_BLOCKED,"팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요.");try{const t=Ge(e.issuer);if(!e.clientId)throw new _(h.INVALID_CONFIG,"ONE ID clientId가 비어 있습니다");this.cancelPending("새 ONE ID 로그인 요청으로 이전 대기를 중단했습니다");const n=new Si,i=o=>n.abort(o);this.abortPending=i;try{return r?await this.authorizeWithPopup(r,{...e,issuer:t},n):await this.authorizeWithRedirect({...e,issuer:t},n)}finally{this.abortPending===i&&(this.abortPending=null)}}catch(t){try{r==null||r.close()}catch{}throw t}}async completeRedirect(e,r){const t=Ge(e.issuer),n=this.takePending(),i=new URL(r).searchParams;if(!n||n.issuer!==t||n.clientId!==e.clientId)throw new _(h.ONEID_STATE_MISMATCH,"진행 중인 ONE ID 로그인이 없습니다. 다시 로그인해 주세요.");if(this.now()-n.createdAt>xi)throw new _(h.ONEID_TIMEOUT,"ONE ID 로그인 시간이 지났습니다");const o=i.get("state");if(!o||o!==n.state)throw new _(h.ONEID_STATE_MISMATCH,"ONE ID 로그인 결과의 state가 다릅니다");if(i.get("iss")!==t)throw new _(h.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다");const a=i.get("error");if(a){const d=i.get("error_description")??void 0;throw new _(jr(a),d||`ONE ID 인가 오류: ${a}`,{error:a,error_description:d})}const c=i.get("code");if(!c)throw new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다");return{tokens:await this.exchangeCode({...e,issuer:t},c,n.codeVerifier,n.redirectUri,n.nonce),returnTo:Kt(n.returnTo)}}async refresh(e,r){const t=Ge(e.issuer),n=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:r});let i;try{i=await this.fetchImpl(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})}catch(c){throw new _(h.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",c)}const o=await Vt(i);if(!i.ok){if(i.status===400&&o.error==="invalid_grant"){const c=typeof o.error_reason=="string"?o.error_reason:void 0;throw new _(yi(c),"ONE ID 세션이 끝났습니다. 다시 로그인해 주세요.",{error:"invalid_grant",error_reason:c})}throw i.status>=400&&i.status<500&&i.status!==408&&i.status!==429?new _(h.ONEID_SESSION_INVALID,"ONE ID 세션을 갱신할 수 없습니다. 다시 로그인해 주세요.",{status:i.status,error:o.error}):new _(h.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",{status:i.status,error:o.error})}const a=Xr(o,this.now());return{...a,refreshToken:a.refreshToken??r}}async logout(e,r){const t=Ge(e.issuer);let n;try{n=await this.fetchImpl(`${t}/logout`,{method:"POST",headers:{Authorization:`Bearer ${r}`}})}catch(i){throw new _(h.NETWORK_ERROR,"ONE ID 로그아웃 요청을 보내지 못했습니다",i)}if(!n.ok&&n.status!==401)throw new _(h.NETWORK_ERROR,"ONE ID 로그아웃 요청이 실패했습니다",{status:n.status})}openBlankPopup(e=500,r=700){const t=Math.max(e,500),n=Math.max(r,700),i=window.screenX+(window.outerWidth-t)/2,o=window.screenY+(window.outerHeight-n)/2;try{return this.popupSeq+=1,window.open("about:blank",`ONEidLogin${this.popupSeq}`,`width=${t},height=${n},left=${i},top=${o}`)}catch{return null}}async pushAuthorizationRequest(e,r,t,n,i){const o=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:r,scope:e.scope??fi,state:t,nonce:n,code_challenge:i,code_challenge_method:"S256"});let a;try{a=await this.fetchImpl(`${e.issuer}/par`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})}catch(l){throw new _(h.NETWORK_ERROR,"ONE ID 로그인 요청을 보내지 못했습니다",l)}const c=await Vt(a);if(!a.ok||typeof c.request_uri!="string")throw new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 요청이 거부되었습니다",{status:a.status,error:c.error});return c.request_uri}authorizeUrl(e,r){const t=new URL(`${e.issuer}/authorize`);return t.searchParams.set("client_id",e.clientId),t.searchParams.set("request_uri",r),t.toString()}async exchangeCode(e,r,t,n,i){const o=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:r,redirect_uri:n,code_verifier:t});let a;try{a=await this.fetchImpl(`${e.issuer}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o})}catch(d){throw new _(h.NETWORK_ERROR,"ONE ID 토큰을 받지 못했습니다",d)}const c=await Vt(a);if(!a.ok)throw new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 토큰 교환이 거부되었습니다",{status:a.status,error:c.error});const l=Xr(c,this.now());if(l.idToken){const d=Yr(l.idToken);if(!d||d.iss!==e.issuer||d.nonce!==i)throw new _(h.ONEID_ISSUER_MISMATCH,"ONE ID id_token의 발급자나 nonce가 요청과 다릅니다")}return l}async authorizeWithPopup(e,r,t){const n=new URL(r.issuer).origin,i=`${r.issuer}${hi}`,o=ft(),a=ft(),c=zr(),l=await Jr(c),d=await this.pushAuthorizationRequest(r,i,o,a,l);t.throwIfAborted(),u.log("[CROSSx] ONE ID 로그인 팝업 이동",{issuer:r.issuer,clientId:r.clientId}),e.location.href=this.authorizeUrl(r,d);const p=await new Promise((g,w)=>{let m=0,x=!0;const S=()=>{t.onAbort=null,clearTimeout(U),clearInterval(C),window.removeEventListener("message",L)},I=H=>{S(),w(H)},U=setTimeout(()=>{I(new _(h.ONEID_TIMEOUT,"ONE ID 로그인 응답 시간이 지났습니다"))},gi),C=setInterval(()=>{if(!x)return;m++;let H;try{H=e.closed}catch{x=!1;return}if(!H)return;const G=typeof document<"u"&&document.hasFocus();if(m<=mi&&!G){u.warn("[CROSSx] ONE ID 팝업 closed 오탐 가능성(COOP) — 결과 대기 유지"),x=!1;return}I(new _(h.USER_REJECTED,"ONE ID 로그인이 취소되었습니다"))},wi),L=H=>{if(H.origin!==n||H.source!==e||!bi(H.data))return;const G=H.data;if(G.state!==o){u.warn("[CROSSx] ONE ID 결과 state가 현재 요청과 달라 무시합니다");return}try{e.postMessage({type:_i,state:o},n)}catch{}if(G.iss!==r.issuer){I(new _(h.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다"));return}if(G.type===qr||G.error){const q=G.error??"unknown_error";u.warn("[CROSSx] ONE ID 인가 오류:",q),I(new _(jr(q),G.error_description||`ONE ID 인가 오류: ${q}`,{error:q,error_description:G.error_description}));return}if(!G.code){I(new _(h.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다"));return}S(),g(G.code)};t.onAbort=H=>{I(new _(h.USER_REJECTED,H))},window.addEventListener("message",L)}),f=await this.exchangeCode(r,p,c,i,a);return u.log("[CROSSx] ONE ID 로그인 완료 (팝업)"),{status:"completed",tokens:f,returnTo:Kt(r.returnTo)}}async authorizeWithRedirect(e,r){const t=e.redirectUri??`${window.location.origin}/auth/callback`;if(new URL(t).origin!==window.location.origin)throw new _(h.INVALID_CONFIG,"ONE ID redirectUri는 지금 페이지와 같은 origin이어야 합니다");const n=ft(),i=ft(),o=zr(),a=await Jr(o),c=await this.pushAuthorizationRequest(e,t,n,i,a);r.throwIfAborted();const l={issuer:e.issuer,clientId:e.clientId,state:n,nonce:i,codeVerifier:o,redirectUri:t,returnTo:Kt(e.returnTo),createdAt:this.now()};this.pendingStorage.setItem(Gt,JSON.stringify(l)),u.log("[CROSSx] ONE ID 로그인 같은 창 이동",{issuer:e.issuer,clientId:e.clientId});const d=this.authorizeUrl(e,c);return(this.options.navigate??(p=>window.location.assign(p)))(d),{status:"redirecting"}}takePending(){const e=this.pendingStorage.getItem(Gt);if(this.pendingStorage.removeItem(Gt),!e)return null;try{const r=JSON.parse(e);return typeof(r==null?void 0:r.state)=="string"&&typeof r.codeVerifier=="string"?r:null}catch{return null}}}async function Vt(s){try{const e=await s.json();return typeof e=="object"&&e!==null?e:{}}catch{return{}}}const gt="crossx.oneid.session",Zr=60*1e3,Qr=new Set([h.ONEID_SESSION_EVICTED,h.ONEID_SESSION_REVOKED,h.ONEID_SESSION_EXPIRED,h.ONEID_SESSION_INVALID]);class Ei{constructor(e,r,t,n=()=>Date.now()){this.port=e,this.config=r,this.storage=t,this.now=n,this.refreshing=null,this.generation=0}save(e){this.generation+=1;const r={issuer:Ge(this.config.issuer),clientId:this.config.clientId,tokens:e};return this.storage.setItem(gt,JSON.stringify(r)),es(r)}async get(){const e=await this.ensureFresh();return e?es(e):null}async getAccessToken(){const e=await this.ensureFresh();if(!e)throw new _(h.AUTH_NOT_AUTHENTICATED,"ONE ID로 로그인하지 않았습니다");return e.tokens.accessToken}async signOut(){const e=this.read();if(this.clear(),!e)return;let r=e.tokens.accessToken;if(e.tokens.refreshToken&&e.tokens.expiresAt-Zr<=this.now())try{r=(await this.port.refresh(this.config,e.tokens.refreshToken)).accessToken}catch(t){if(t instanceof _&&Qr.has(t.code))return}await this.port.logout(this.config,r)}clear(){this.generation+=1,this.storage.removeItem(gt)}read(){var r;const e=this.storage.getItem(gt);if(!e)return null;try{const t=JSON.parse(e);return typeof((r=t==null?void 0:t.tokens)==null?void 0:r.accessToken)=="string"&&typeof t.tokens.expiresAt=="number"&&t.issuer===Ge(this.config.issuer)&&t.clientId===this.config.clientId?t:(this.clear(),null)}catch{return this.clear(),null}}async ensureFresh(){const e=this.read();if(!e)return null;if(e.tokens.expiresAt-Zr>this.now())return e;if(!e.tokens.refreshToken){if(e.tokens.expiresAt>this.now())return e;throw this.clear(),new _(h.ONEID_SESSION_EXPIRED,"ONE ID 로그인이 만료되었습니다. 다시 로그인해 주세요.")}return this.refreshing??(this.refreshing=this.refresh(e).finally(()=>{this.refreshing=null})),this.refreshing}async refresh(e){const r=this.generation;try{const t=await this.port.refresh(this.config,e.tokens.refreshToken),n={...e,tokens:t};if(r!==this.generation)throw new _(h.AUTH_NOT_AUTHENTICATED,"ONE ID 세션이 바뀌었습니다");return this.storage.setItem(gt,JSON.stringify(n)),n}catch(t){if(r!==this.generation)throw t;if(t instanceof _&&Qr.has(t.code))throw this.clear(),t;if(e.tokens.expiresAt>this.now())return e;throw t}}}function es(s){const e=s.tokens.idToken?Yr(s.tokens.idToken):null;return{subject:typeof(e==null?void 0:e.sub)=="string"?e.sub:"",clientId:s.clientId,issuer:s.issuer,scope:s.tokens.scope,expiresAt:s.tokens.expiresAt}}function Ii(s){return s==="local"?window.localStorage:window.sessionStorage}const Ai=3,Ti=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function Ri(s){return s.code===Ai||/execution reverted/i.test(s.message??"")}class Ni{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error){const{code:c,message:l}=a.error,d={method:e,chainId:t,code:c,message:l,data:a.error.data},p=Ri(a.error);throw p&&typeof d.data=="string"&&Ti.test(d.data)&&(d.revertData=d.data,d.selector=d.data.slice(0,10).toLowerCase()),new _(p?h.EXECUTION_REVERTED:h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${l} (코드: ${c})`,d)}return a==null?void 0:a.result}}class Ci{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}function Oi(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const r=new Uint8Array(16);return globalThis.crypto.getRandomValues(r),Array.from(r).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class fe{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return u.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return u.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await fe.waitForBridgeReady(5e3)||u.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=fe.getBridge(),!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw u.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new _(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,u.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=Oi(),r=Date.now(),t={version:1,appId:this.config.appId,appVersion:this.config.appVersion,sdkVersion:this.config.sdkVersion,keyId:this.config.keyId,userIdHash:this.config.userIdHash,nonce:e,timestamp:r,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new _(h.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0,a=n.provider==="google"||n.provider==="apple"?n.provider:void 0;return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),lastActivityAt:Date.now(),walletAddress:n.walletAddress,walletName:o,walletProvider:a}}catch(n){throw u.error("[RNBridge] Handshake failed",n),new _(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),r=(e.expiresAt-Date.now())/1e3;if(r<60)throw new _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:r});return this.touchActivity(),e}catch(e){if(e instanceof _)throw e;const r=e instanceof Error?e.message:String(e);throw r.includes("USER_REJECTED")||r.toLowerCase().includes("rejected")?new _(h.USER_REJECTED,"Firebase ID token request rejected by user",e):(u.error("[RNBridge] Firebase token request failed",e),new _(h.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof _?e:(u.error("[RNBridge] Fresh Firebase token request failed",e),new _(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new _(h.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const r=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((r.expiresAt-Date.now())/1e3<60)throw new _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return r}catch(r){throw r instanceof _?r:(u.warn("[RNBridge] Session restore Firebase token request failed",r),new _(h.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",r))}}getContext(){return this.context}isActive(){var r;if(!((r=this.context)!=null&&r.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new _(h.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var xt={environment:"production"};const Ke={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:""},staging:{oauthServiceUrl:"https://stg-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://stg-oauth2.onechain.nexus"},development:{oauthServiceUrl:"https://dev-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://dev-oauth2.onechain.nexus"}};function ki(s){const e=s.environment,r=e&&e in Ke?Ke[e]:null;if(!r)return null;const t=s.overrides;if(!t)return r;const n={...r};for(const[i,o]of Object.entries(t))typeof o=="string"&&o.trim()!==""&&(n[i]=o);return n}function wt(){try{if(typeof xt<"u"){const s=typeof xt=="string"?JSON.parse(xt):xt,e=ki(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Ke)return Ke[s]}catch{}return Ke.production}function ts(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function Pi(s,e=$t){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Dr),n=r/t,o=(r%t).toString().padStart(Dr,"0"),a=ts(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function mt(s,e,r,t=$t){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=ts(c.slice(0,t)),d=l?`${o}.${l}`:`${o}`;return e?`${d} ${e}`:d}catch{return}}function Di(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Pr)throw new _(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Pr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Li(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function Bi(s,e){const r=Mi(e);if(s==="0"){if(r!==void 0&&r!==0)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${r}`);return}const t=s.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(r===void 0)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(r!==n)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${r})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function Mi(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const r=e.chainId;if(r==null)return;const t=Number(r);return Number.isFinite(t)?t:void 0}class Ve{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new _(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){var c,l;if((l=(c=this.deps).isRNBridgeMode)!=null&&l.call(c))return;if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((d,p)=>{i=d,o=p});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const p=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!p)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(p),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const d=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async p=>{this.deps.pinStore.set(p);try{return await this.deps.walletProvider.verifyPin(p)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(f){if(this.deps.pinStore.clear(),f instanceof _){if(f.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(f.code===h.PIN_INVALID)return{ok:!1,error:f.message};if(f.code===h.PIN_LOCKED)return Ve.buildPinLockedResult(f,a)}throw f}}});if(!d)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(d),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(d){if(d instanceof _&&(d.code===h.AUTH_NOT_AUTHENTICATED||d.code===h.AUTH_TOKEN_EXPIRED||d.code===h.SESSION_EXPIRED)&&d.code!==h.SESSION_EXPIRED){const p=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:f?this.deps.maskEmail(f,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(d),d}throw o(d),d}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof _){if(t=Ve.parsePinError(n,r),!t)throw n}else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof _&&(t=Ve.parsePinError(n,r),t))continue;throw n}}}static parsePinError(e,r){if(e.code===h.PIN_WRONG)return{errorMessage:r.pin_input_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:r.pin_locked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:r.pin_input_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,r){const t=Ve.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class $i{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){var t,n;if((n=(t=this.deps).isRNBridgeMode)!=null&&n.call(t))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new _(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let i;return this.deps.walletProvider.prepare&&(i=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(i)})}}function Ui(s){return s==="google"||s==="apple"}class Fi{constructor(e){this.deps=e}async signInAgain(){var r,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=Ui(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){u.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{u.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return u.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof _&&r.code===h.WITHDRAW_FAILED){if(u.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof _&&r.code===h.WALLET_NOT_FOUND){if(u.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof _)||r.code!==h.SESSION_EXPIRED)throw r;if(u.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new _(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new _(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Wi{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r,t){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const o=await this.deps.walletProvider.getAddresses(n);if(o.length>0){let c,l=!1;if(r){const p=o.find(f=>f.address.toLowerCase()===r.toLowerCase());p?c=p:(c={address:r,index:0},l=!0)}else e!==void 0?c=o.find(p=>p.index===e)??o[0]:c=o[0];l?u.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const d=!!r&&!!t&&c.address.toLowerCase()===r.toLowerCase();this.deps.setActiveWallet(c.address,c.index,d?{walletName:t}:void 0);return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const a=await this.deps.walletProvider.getAddress(n,0);u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",a.address),this.deps.setActiveWallet(a.address,0)}}class Hi{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const d=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(d===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,d,e));if(!p){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=d;break}if(p.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=d;break}const f=p.pinStatus;if(o=f.maxAttempts,i=o-f.remainingAttempts,f.remainingAttempts===0&&f.lockExpiresAt){const g=f.lockExpiresAt*1e3,w=Math.max(1,Math.round((g-Date.now())/1e3)),m=w<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${w}초, 메시지: ${m}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,m),i=0,n="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof _))throw p;if(p.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const f=be(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:f.session_alert_title,message:f.alert_session_expired,email:g?this.deps.maskEmail(g,f.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const f=p.details;if(o=(f==null?void 0:f.maxAttempts)??5,(f==null?void 0:f.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const g=((f==null?void 0:f.lockExpiresAt)??0)*1e3,w=Math.max(1,Math.round((g-Date.now())/1e3)),m=w<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${w}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(w,m),i=0,n="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const d=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",d.address),d}catch(d){if(d instanceof _&&d.code===h.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(d instanceof _&&d.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:f?this.deps.maskEmail(f,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){u.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const m=await this.deps.executeMigrate(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",m.address),m}catch(m){throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",m),m}}throw this.deps.clearAuthState(),d}throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",d),d}}}class Gi{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=g=>!(g!=null&&g.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[d,p,f]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const g=f;if(g){const w=kr;c.maxFeePerGas=`0x${(BigInt(g)+BigInt(w)).toString(16)}`,c.maxPriorityFeePerGas=w,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",g,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Vn,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=kr,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ki{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Vi(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class qi{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e,r){var n,i,o,a,c;const t={authenticated:e.success,userId:((n=e.user)==null?void 0:n.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((i=e.user)==null?void 0:i.email)??null,providerSub:((o=e.user)==null?void 0:o.providerSub)??null,loginType:Vi((a=e.user)==null?void 0:a.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(t),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...r?{source:r}:{}})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class zi{constructor(e){this.deps=e}async resolveAddress(e){const r=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===r){if(!t)throw new _(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:r}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Ji{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new _(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new _(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class ji{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const o=this.deps.getProviderSub()??e;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",o);const a=await this.deps.migrationOrchestrator.handleMigrationFlow(o);if(a)return this.deps.setActiveWallet(a.address,0),{address:a.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(r==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const t=await this.tryGetOrCreateWalletWithMigrationFallback(e);return t.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:t.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),u.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address,migrated:!1}}catch(r){if(r instanceof _&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function rs(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Yi{constructor(e){this.deps=e}async registerTokenHistory(e,r,t){if(!(e!=null&&e.trim()))throw new _(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(r!=null&&r.trim()))throw new _(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=r.startsWith("0x")?r:`0x${r}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new _(h.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(t!=null&&t.trim())||t.length>64)throw new _(h.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),o=rs(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{u.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),u.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof _?c:new _(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const r=this.deps.getApiBaseUrl(),t=new URL(rs(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{u.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new _(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),u.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof _?i:new _(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,r,t,n){const i=(n==null?void 0:n.maxRetries)??3,o=(n==null?void 0:n.retryDelayMs)??2e3;for(let a=0;a<i;a++)try{await this.registerTokenHistory(e,r,t);return}catch(c){if(c instanceof _&&c.message.includes("404")&&a<i-1){u.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(d=>setTimeout(d,o));continue}throw c}}handleError(e,r){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:h.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:h.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:h.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new _(n.code,n.message)}}function qt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const r=s.indexOf("@");if(r<0)return"*".repeat(s.length||3);const t=s.substring(0,r),n=s.substring(r);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Re=class Re extends Ci{constructor(e,r,t,n,i,o,a,c,l,d,p,f,g){var w,m;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.pinEncryptor=f,this.oneIdAuth=g,this._warnedUnknownNativeCurrency=new Set,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._sdkDeprecationNotified=!1,this._sdkUnsupportedNotified=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&Wr(e.logger),this.confirmation=l,this.pinStore=p??new Wt,this.stateManager=new qi({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:S,walletName:I})=>{const U={address:x,index:S};I!==void 0&&(U.walletName=I),this.emit("addressChanged",U)},emitAuthChanged:({isAuthenticated:x,address:S,userId:I,source:U})=>{this.emit("authChanged",{isAuthenticated:x,address:S,userId:I,...U?{source:U}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Re.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ve({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:qt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.signingOrchestrator=new $i({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Wi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,S,I)=>this.setActiveWallet(x,S,I)}),this.migrationOrchestrator=new Hi({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,S)=>this.migrateWalletUseCase.execute(x,S),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:qt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new Gi({getActiveAddress:()=>this.address,estimateGas:(x,S)=>this.estimateGas(x,S),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,S,I)=>this.jsonRpc.call(x,S,I)}),this.signatureVerifier=new Ki(this.crypto),this.addressResolverService=new zi({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Ji({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new ji({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,S)=>this.setActiveWallet(x,S),showWalletCreated:()=>{var x,S;return((S=(x=this.confirmation).showWalletCreatedPrompt)==null?void 0:S.call(x))??Promise.resolve()}}),this.tokenHistoryService=new Yi({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Fi({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:x=>{this._isRecoveringSession=x},setAuthenticated:x=>{this.authenticated=x},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:x=>this.signInUseCase.execute(x),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:x=>this.confirmation.showSessionAlert(x),clearAuthState:()=>this.clearAuthState(),applyAuthResult:x=>this.applyAuthResult(x),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:qt}),this.chainRegistry=d,this.jsonRpc=new Ni(d,i),this.signInUseCase=new Ft(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new di(this.internalConfig,t,c,this._config.persistWalletPreference!==!1?[Re.WALLET_PREF_KEY]:[]),this.migrateWalletUseCase=new ui(t,a),(w=a.setOnUnauthorized)==null||w.call(a,()=>this.forceLogout()),(m=a.setTokenRefresher)==null||m.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}handleSdkVersionDeprecation(e){if(this._sdkDeprecationNotified)return;this._sdkDeprecationNotified=!0;const r=ut;console.warn(`[CROSSx] ${r} is deprecated`+(e.sunset?` and will stop working on ${e.sunset}`:"")+". Update @nexus-cross/crossx-sdk-core."+(e.infoUrl?` See ${e.infoUrl}`:"")),this.emit("versionDeprecated",{version:r,sunset:e.sunset,infoUrl:e.infoUrl})}handleSdkVersionUnsupported(e){this._sdkUnsupportedNotified||(this._sdkUnsupportedNotified=!0,console.error(`[CROSSx] ${ut} is no longer supported by the wallet gateway. Update @nexus-cross/crossx-sdk-core.`+(e.message?` (${e.message})`:"")),this.confirmation.showUpdateRequired().catch(r=>{u.warn("[CROSSx] 업데이트 필요 모달 표시 실패:",r)}))}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,u.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(r){u.warn("[CROSSx] 저장된 bridge 세션 마커 제거 실패",r)}}}assertRNBridgeSessionActive(){var e;(e=this._rnBridgeService)==null||e.assertActive()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;u.log("[CROSSx SDK] v2.6.0-beta.1 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=wt();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.legacyOauthServiceUrl=n.legacyOauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Re.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&u.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const l=this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()),d=this._rnBridgeWalletName&&a&&this._rnBridgeWalletAddress&&a.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(l)this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex,d?{walletName:d}:void 0);else try{await this.loadWalletAfterAuth(o,a,d)}catch(p){if(p instanceof _&&p.code===h.PIN_CANCELLED)u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(p instanceof _&&(p.code===h.SESSION_EXPIRED||p.code===h.AUTH_NOT_AUTHENTICATED||p.code===h.USER_NOT_FOUND))u.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",p.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw p}}return this.initialized=!0,u.info("[CROSSx SDK] v2.6.0-beta.1 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new _(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!fe.isAvailable())return null;try{u.log("[CROSSx] RN Bridge 감지 — Handshake 시도"),u.info("[CROSSx][RNBridge trace] Bootstrap config",{appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.6.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new fe({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.6.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this._rnBridgeWalletName=r.walletName,this._rnBridgeWalletProvider=r.walletProvider,this.subscribeBridgeWalletChanged(),u.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)",walletName:r.walletName??"(없음)"});const t=await this.signInUseCase.hasStoredRNBridgeSession();if(t&&(this._isAuthenticatedViaRNBridge=!0,u.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(t){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return u.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return u.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),u.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const r=this._rnBridgeService.getContext(),t=Date.now();u.info("[CROSSx] Bridge 세션 만료 감지 — 재핸드셰이크 시도",{elapsedSinceActivatedMs:r?t-r.activatedAt:"(context 없음)",idleMs:r?t-r.lastActivityAt:"(context 없음)",absoluteTtlMs:(r==null?void 0:r.absoluteTtlMs)??"(context 없음)",idleTtlMs:(r==null?void 0:r.idleTtlMs)??"(context 없음)",absoluteExpired:r?t-r.activatedAt>r.absoluteTtlMs:"(context 없음)",idleExpired:r?t-r.lastActivityAt>r.idleTtlMs:"(context 없음)"});try{const n=Date.now(),i=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=i.walletAddress,this._rnBridgeWalletName=i.walletName,this._rnBridgeWalletProvider=i.walletProvider,u.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-n,walletAddress:i.walletAddress??"(없음)",walletName:i.walletName??"(없음)",absoluteTtlMs:i.absoluteTtlMs,idleTtlMs:i.idleTtlMs})}catch(n){return u.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",n),this._rnBridgeService=null,null}}try{const r=await this._rnBridgeService.requestFirebaseIdToken();u.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),u.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof _&&r.code===h.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),u.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):r instanceof _&&r.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(u.warn("[CROSSx] Bridge 로그인 타임아웃/실패",r),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;u.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const r=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,u.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=t.user)==null?void 0:e.id}),t):(this._isAuthenticatedViaRNBridge=!1,u.warn("[CROSSx] RN Bridge 세션 복원 실패:",t.error),null)}catch(r){return this._isAuthenticatedViaRNBridge=!1,u.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",r),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new _(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore()}catch(e){throw u.error("[CROSSx] Bridge session restore token request failed:",e),new _(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return fe.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const r=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(r&&u.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!r){const n=await this._tryBridgeSignIn();if(n===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(n!=null&&n.success)return n}let t=e;if(!(e!=null&&e.provider)){const n=await this.confirmation.showLoginSelector({connectOtherWallets:Qn(this._config)});if(n===null)return{success:!1,error:"User cancelled login"};if(n.type==="external")throw this.emit("connectExternalWallet",{walletId:n.walletId}),new _(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");t={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(t);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof _?n:new _(h.AUTH_FAILED,"로그인에 실패했습니다",n)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof _&&i.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){var t,n;if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r;try{r=await this.signInUseCase.executeWithOAuthToken(e),r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r,"external"),(n=(t=this.oauth).cancelPending)==null||n.call(t,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof _?i:new _(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c);return{...r,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i);return{...r,address:(o==null?void 0:o.address)??r.address,addresses:i}}catch(i){throw i instanceof _&&i.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>u.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",o))),i}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t)),t}catch(t){throw t instanceof _?t:new _(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}signInWithOneId(e){var o,a;let r;try{r=this.oneIdContext()}catch(c){return Promise.reject(c)}const{port:t,config:n,sessions:i}=r;return t.authorize({...n,mode:(e==null?void 0:e.mode)??((o=this._config.oneId)==null?void 0:o.mode)??"auto",redirectUri:(a=this._config.oneId)==null?void 0:a.redirectUri,returnTo:e==null?void 0:e.returnTo}).then(c=>c.status==="redirecting"?c:{status:"signed-in",session:i.save(c.tokens),returnTo:c.returnTo})}async completeOneIdSignIn(e=window.location.href){const{port:r,config:t,sessions:n}=this.oneIdContext(),{tokens:i,returnTo:o}=await r.completeRedirect(t,e);return{session:n.save(i),returnTo:o}}async getOneIdSession(){return this.oneIdContext().sessions.get()}async getOneIdAccessToken(){return this.oneIdContext().sessions.getAccessToken()}async signOutOneId(){await this.oneIdContext().sessions.signOut()}oneIdContext(){this.ensureInitialized();const e=this._config.oneId;if(!this.oneIdAuth||!(e!=null&&e.clientId))throw new _(h.NOT_IMPLEMENTED,"이 환경에서는 ONE ID 로그인을 사용할 수 없습니다 (SDKConfig.oneId 필요)");const r=e.issuer||wt().oneIdIssuer;if(!r)throw new _(h.NOT_IMPLEMENTED,"ONE ID issuer가 정해지지 않았습니다. SDKConfig.oneId.issuer를 지정하세요");const t={issuer:r,clientId:e.clientId,scope:e.scope};return this._oneIdSessions??(this._oneIdSessions=new Ei(this.oneIdAuth,t,Ii(e.storage))),{port:this.oneIdAuth,config:t,sessions:this._oneIdSessions}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=fe.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),u.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){u.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}}catch(e){throw new _(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}getRNBridgeActiveWallet(){return this._rnBridgeWalletAddress?{address:this._rnBridgeWalletAddress,walletName:this._rnBridgeWalletName}:null}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this._tryBridgeSessionRestore();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName)}catch(t){t instanceof _&&t.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",t)}return!0}const r=await this.signInUseCase.restoreSession();if(r!=null&&r.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(r);try{await this.loadWalletAfterAuth()}catch(t){t instanceof _&&t.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",t)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),u.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof _?r:new _(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e,r){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let t=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));t.length===0&&this.address&&(t=[{address:this.address,index:0}]);const n=await this.confirmation.showWalletSelector(t,async()=>{await this.pinOrchestrator.ensurePinForSigning();const i=t.length,a={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,i)))).address,index:i};return t.push(a),a},e,r);return n&&this.setActiveWallet(n.address,n.index),n}async selectWalletIfMultiple(e,r){if(e.length<2)return null;const t=this._isAuthenticatedViaRNBridge?this._rnBridgeWalletAddress??this.address??void 0:void 0,n=!t&&this._config.persistWalletPreference!==!1?await this.storage.get(Re.WALLET_PREF_KEY).catch(()=>null):null,i=t?[t,r]:[r,n==null?void 0:n.address];for(const o of i){if(typeof o!="string"||!o)continue;const a=e.find(c=>c.address.toLowerCase()===o.toLowerCase());if(a)return this.setActiveWallet(a.address,a.index),a}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof _?r:new _(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(be(e))}setPinKeyboard(e){var r,t;this._config=Object.freeze({...this._config,pinKeyboard:e}),(t=(r=this.confirmation).setPinKeyboard)==null||t.call(r,e)}resolveNativeCurrency(e){const r=oi(e,this._config.nativeCurrencies);return r||(this._warnedUnknownNativeCurrency.has(e)||(this._warnedUnknownNativeCurrency.add(e),console.warn(`[CROSSx SDK] ${e} 의 native 통화 정보가 없어 심볼을 비우고 decimals 를 18 로 가정합니다. 컨펌 모달 금액이 단위 없이 표시되며, decimals 가 18 이 아니면 금액이 틀립니다. SDKConfig.nativeCurrencies 에 { '${e}': { symbol, decimals } } 를 넘겨 주세요.`)),ii)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){const n=fe.getBridge(),i=this._isAuthenticatedViaRNBridge||!this.authenticated;if(n!=null&&n.signMessage&&i)try{const a=await n.signMessage({chainId:e,message:r,from:this.address??"",index:(t==null?void 0:t.index)??0,dappName:(t==null?void 0:t.dappName)??this._config.appName});return{chainId:e,signature:a.signature,message:r,address:this.address??""}}catch(a){if(!Ur(a))throw He(a,h.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),u.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const o=await this.resolveAddress(t==null?void 0:t.index);try{const a=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:o.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:o.address},execute:c=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,c,o.address)});return this.signatureVerifier.verifySignatureSigner(r,a.signature,o.address),{chainId:e,signature:a.signature,message:r,address:o.address}}catch(a){throw a instanceof _?a:new _(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,a)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Bi(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:r,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return Di(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof _?i:new _(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(Re.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=this.resolveNativeCurrency(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:a=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a)});return Li(o.signature),{chainId:e,signedTx:o.signature,txHash:o.txHash??""}}catch(o){if(o instanceof _)throw o;const a=o instanceof Error?o.message:String(o);throw new _(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,o)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=this.resolveNativeCurrency(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async d=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,d)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,d);return p.txHash??p.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,ut).catch(d=>u.log("[TokenHistory] register failed (non-critical):",d)),{chainId:e,txHash:o,status:"pending"}}catch(o){if(o instanceof _)throw o;const a=o instanceof Error?o.message:String(o);throw new _(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,o)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??Gn,i=Kn,o=t.timeoutMs??Or,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,i)}throw new _(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var m,x;if(this._isAuthenticatedViaRNBridge){const S=fe.getBridge();if(S!=null&&S.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(S,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((m=this._config.receiptPolling)==null?void 0:m.intervalMs)??Hn,l=i??((x=this._config.receiptPolling)==null?void 0:x.timeoutMs)??Or,d=this.resolveNativeCurrency(e),p=r.from??"";let f,g;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{f=S;const I=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),U=r.value?BigInt(r.value):0n,C=mt(r.value,d.symbol,d.decimals,this._config.displayDecimals),L=mt("0x"+I.toString(16),d.symbol,d.decimals,this._config.displayDecimals),H=mt("0x"+(U+I).toString(16),d.symbol,d.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:S.from,to:S.to??r.to,amount:C,fees:L,total:H,nativeSymbol:d.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(g=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:p,to:r.to,amount:mt(r.value,d.symbol,d.decimals,this._config.displayDecimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},w),g)throw g;return{chainId:e,txHash:a,receipt:f}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){let i;try{i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs})}catch(o){throw He(o,h.TRANSACTION_FAILED)}return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}isPinRequired(){return!this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new _(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof _?n:new _(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){if(n instanceof _&&n.code===h.EXECUTION_REVERTED)throw n;const i=n instanceof Error?n.message:String(n);throw new _(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:Pi(n,this._config.displayDecimals),chainId:e}}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){this.ensureAuthenticated();let r=this._providers.get(e);return r||(r=new Ut(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){u.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof _)throw n;const i=n instanceof Error?n.message:String(n);throw new _(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}setActiveWallet(e,r,t){const n=this.address;this.stateManager.setActiveWallet(e,r,t),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=fe.getBridge();if(!(e!=null&&e.onEvent)){u.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){u.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){u.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){u.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){u.warn("[walletChanged] invalid source — 이벤트 무시",t);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){u.warn("[walletChanged] not authenticated — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(u.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),u.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,r){this.stateManager.applyAuthResult(e,r)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r,t){return this.walletLifecycleService.loadWalletAfterAuth(e,r,t)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,r,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,r,t))}async getTokenHistory(e){return this.withSessionRecovery(()=>this.tokenHistoryService.getTokenHistory(e))}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Wr(null)}};Re.WALLET_PREF_KEY="wallet_preference",Re.OFFCHAIN_CHAIN_ID="0";let tt=Re;class Xi{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return u.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw u.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw u.error("Storage clear error:",e),e}}}const yt="crossx-sdk",ss=1,he="data",Ne="keys",bt="aes-primary",Zi=12;class ns{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,r)=>{const t=indexedDB.open(this.dbName,ss);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(he)||n.createObjectStore(he),n.objectStoreNames.contains(Ne)||n.createObjectStore(Ne)},t.onsuccess=()=>e(t.result),t.onerror=()=>r(t.error)})}openLegacyIfExists(){return new Promise((e,r)=>{let t=!1;const n=indexedDB.open(yt,ss);n.onupgradeneeded=()=>{t=!0},n.onsuccess=()=>{const i=n.result;if(t){i.close(),this.deleteDB(yt).then(()=>e(null));return}if(!i.objectStoreNames.contains(Ne)||!i.objectStoreNames.contains(he)){i.close(),e(null);return}e(i)},n.onerror=()=>r(n.error)})}deleteDB(e){return new Promise(r=>{const t=indexedDB.deleteDatabase(e);t.onsuccess=()=>r(),t.onerror=()=>{u.warn("[CROSSx] IndexedDB 삭제 실패:",e,t.error),r()},t.onblocked=()=>{u.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),r()}})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,bt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,bt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===yt)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const r=e.transaction([Ne,he],"readonly"),t=r.objectStore(Ne).get(bt),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const i=r.objectStore(he).getAll(),o=r.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)}),new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)})]);e.close(),await this.idbPut(Ne,bt,n);for(let l=0;l<c.length;l++)await this.idbPut(he,String(c[l]),a[l]);return await this.deleteDB(yt),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Zi);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(he,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(he,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return u.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(he,e)}catch(r){throw u.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(he)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const zt=crypto,is=s=>s instanceof CryptoKey,St=new TextEncoder,rt=new TextDecoder;function Qi(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const eo=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Ce=s=>{let e=s;e instanceof Uint8Array&&(e=rt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return eo(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class se extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}se.code="ERR_JOSE_GENERIC";class pe extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}pe.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Jt extends se{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}Jt.code="ERR_JWT_EXPIRED";class os extends se{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}os.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends se{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class to extends se{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}to.code="ERR_JWE_DECRYPTION_FAILED";class ro extends se{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ro.code="ERR_JWE_INVALID";class re extends se{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}re.code="ERR_JWS_INVALID";class xe extends se{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class so extends se{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}so.code="ERR_JWK_INVALID";class jt extends se{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}jt.code="ERR_JWKS_INVALID";class Yt extends se{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Yt.code="ERR_JWKS_NO_MATCHING_KEY";class as extends se{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}as.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class cs extends se{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}cs.code="ERR_JWKS_TIMEOUT";class ls extends se{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}ls.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function st(s,e){return s.name===e}function Xt(s){return parseInt(s.name.slice(4),10)}function no(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function io(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function oo(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!st(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Xt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!st(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Xt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!st(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Xt(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!st(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!st(s.algorithm,"ECDSA"))throw we("ECDSA");const t=no(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}io(s,r)}function ds(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const us=(s,...e)=>ds("Key must be ",s,...e);function hs(s,e,...r){return ds(`Key for the ${s} algorithm must be `,e,...r)}const ps=s=>is(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",vt=["CryptoKey"],ao=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function co(s){return typeof s=="object"&&s!==null}function Se(s){if(!co(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const lo=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function qe(s){return Se(s)&&typeof s.kty=="string"}function uo(s){return s.kty!=="oct"&&typeof s.d=="string"}function ho(s){return s.kty!=="oct"&&typeof s.d>"u"}function po(s){return qe(s)&&s.kty==="oct"&&typeof s.k=="string"}function _o(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new ge('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ge('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const _s=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=_o(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,zt.subtle.importKey("jwk",n,...t)},fs=s=>Ce(s);let ze,Je;const gs=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",Et=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await _s({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},fo={normalizePublicKey:(s,e)=>{if(gs(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?fs(r.k):(Je||(Je=new WeakMap),Et(Je,s,r,e))}return qe(s)?s.k?Ce(s.k):(Je||(Je=new WeakMap),Et(Je,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(gs(s)){let r=s.export({format:"jwk"});return r.k?fs(r.k):(ze||(ze=new WeakMap),Et(ze,s,r,e))}return qe(s)?s.k?Ce(s.k):(ze||(ze=new WeakMap),Et(ze,s,s,e,!0)):s}};async function xs(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Ce(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return _s({...s,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const je=s=>s==null?void 0:s[Symbol.toStringTag],Zt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},go=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&qe(e)){if(po(e)&&Zt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!ps(e))throw new TypeError(hs(s,e,...vt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${je(e)} instances for symmetric algorithms must be of type "secret"`)}},xo=(s,e,r,t)=>{if(t&&qe(e))switch(r){case"sign":if(uo(e)&&Zt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ho(e)&&Zt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!ps(e))throw new TypeError(hs(s,e,...vt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${je(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${je(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${je(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${je(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${je(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function ws(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?go(e,r,t,s):xo(e,r,t,s)}ws.bind(void 0,!1);const ms=ws.bind(void 0,!0);function wo(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new ge(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const mo=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function yo(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function bo(s,e,r){if(e=await fo.normalizePublicKey(e,s),is(e))return oo(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(us(e,...vt));return zt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(us(e,...vt,"Uint8Array","JSON Web Key"))}const So=async(s,e,r,t)=>{const n=await bo(s,e,"verify");lo(s,n);const i=yo(s,n.algorithm);try{return await zt.subtle.verify(i,n,r,t)}catch{return!1}};async function vo(s,e,r){if(!Se(s))throw new re("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new re('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new re("JWS Protected Header incorrect type");if(s.payload===void 0)throw new re("JWS Payload missing");if(typeof s.signature!="string")throw new re("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new re("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const m=Ce(s.protected);t=JSON.parse(rt.decode(m))}catch{throw new re("JWS Protected Header is invalid")}if(!ao(t,s.header))throw new re("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=wo(re,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new re('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new re('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&mo("algorithms",r.algorithms);if(c&&!c.has(a))throw new os('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new re("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new re("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,ms(a,e,"verify"),qe(e)&&(e=await xs(e,a))):ms(a,e,"verify");const d=Qi(St.encode(s.protected??""),St.encode("."),typeof s.payload=="string"?St.encode(s.payload):s.payload);let p;try{p=Ce(s.signature)}catch{throw new re("Failed to base64url decode the signature")}if(!await So(a,e,p,d))throw new ls;let g;if(o)try{g=Ce(s.payload)}catch{throw new re("Failed to base64url decode the payload")}else typeof s.payload=="string"?g=St.encode(s.payload):g=s.payload;const w={payload:g};return s.protected!==void 0&&(w.protectedHeader=t),s.header!==void 0&&(w.unprotectedHeader=s.header),l?{...w,key:e}:w}async function Eo(s,e,r){if(s instanceof Uint8Array&&(s=rt.decode(s)),typeof s!="string")throw new re("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new re("Invalid Compact JWS");const a=await vo({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Io=s=>Math.floor(s.getTime()/1e3),ys=60,bs=ys*60,Qt=bs*24,Ao=Qt*7,To=Qt*365.25,Ro=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ss=s=>{const e=Ro.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*ys);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*bs);break;case"day":case"days":case"d":n=Math.round(r*Qt);break;case"week":case"weeks":case"w":n=Math.round(r*Ao);break;default:n=Math.round(r*To);break}return e[1]==="-"||e[4]==="ago"?-n:n},vs=s=>s.toLowerCase().replace(/^application\//,""),No=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Co=(s,e,r={})=>{let t;try{t=JSON.parse(rt.decode(e))}catch{}if(!Se(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||vs(s.typ)!==vs(n)))throw new pe('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),o!==void 0&&d.push("iss");for(const w of new Set(d.reverse()))if(!(w in t))throw new pe(`missing required "${w}" claim`,t,w,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new pe('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new pe('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!No(t.aud,typeof c=="string"?[c]:c))throw new pe('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=Ss(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:f}=r,g=Io(f||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new pe('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new pe('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>g+p)throw new pe('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new pe('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=g-p)throw new Jt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const w=g-t.iat,m=typeof l=="number"?l:Ss(l);if(w-p>m)throw new Jt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(w<0-p)throw new pe('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Oo(s,e,r){var o;const t=await Eo(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new xe("JWTs MUST NOT use unencoded payload");const i={payload:Co(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function ko(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new ge('Unsupported "alg" value for a JSON Web Key Set')}}function Po(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Do)}function Do(s){return Se(s)}function Es(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Lo{constructor(e){if(this._cached=new WeakMap,!Po(e))throw new jt("JSON Web Key Set malformed");this._jwks=Es(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=ko(t),o=this._jwks.keys.filter(l=>{let d=i===l.kty;if(d&&typeof n=="string"&&(d=n===l.kid),d&&typeof l.alg=="string"&&(d=t===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(t){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":d=l.crv==="Ed25519";break;case"EdDSA":d=l.crv==="Ed25519"||l.crv==="Ed448";break}return d}),{0:a,length:c}=o;if(c===0)throw new Yt;if(c!==1){const l=new as,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await Is(d,p,t)}catch{}},l}return Is(this._cached,a,t)}}async function Is(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await xs({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new jt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function As(s){const e=new Lo(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Es(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Bo=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new cs:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new se("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new se("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Mo(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let er;(typeof navigator>"u"||!((Fn=(Mt=navigator.userAgent)==null?void 0:Mt.startsWith)!=null&&Fn.call(Mt,"Mozilla/5.0 ")))&&(er="jose/v5.10.0");const tr=Symbol();function $o(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Uo{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[tr])!==void 0&&(this._cache=r==null?void 0:r[tr],$o(r==null?void 0:r[tr],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=As(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Yt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Mo()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);er&&!e.has("User-Agent")&&(e.set("User-Agent",er),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Bo(this._url,this._timeoutDuration,this._options).then(r=>{this._local=As(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Fo(s,e){const r=new Uo(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Wo=Ce;function Ho(s){if(typeof s!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=Wo(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(rt.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rr(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function ee(s,e,r=""){const t=rr(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Ts(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Ye(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Rs(s,e){ee(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Go(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Xe(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function sr(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const Ko=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Vo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function qo(s){for(let e=0;e<s.length;e++)s[e]=Vo(s[e]);return s}const Ns=Ko?s=>s:qo,Cs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zo=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function nt(s){if(ee(s),Cs)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=zo[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Os(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function It(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Cs)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=Os(s.charCodeAt(i)),a=Os(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Oe(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];ee(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function ks(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Ps(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Jo=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function jo(s,e,r){return s&e^~s&r}function Yo(s,e,r){return s&e^s&r^e&r}class Xo{constructor(e,r,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=sr(this.buffer)}update(e){Ye(this),ee(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=sr(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ye(this),Rs(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Xe(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)r[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=sr(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,d[p],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ke=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),At=BigInt(2**32-1),Ds=BigInt(32);function Zo(s,e=!1){return e?{h:Number(s&At),l:Number(s>>Ds&At)}:{h:Number(s>>Ds&At)|0,l:Number(s&At)|0}}function Qo(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=Zo(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const ea=(s,e,r)=>s<<r|e>>>32-r,ta=(s,e,r)=>e<<r|s>>>32-r,ra=(s,e,r)=>e<<r-32|s>>>64-r,sa=(s,e,r)=>s<<r-32|e>>>64-r,na=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pe=new Uint32Array(64);class ia extends Xo{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let p=0;p<16;p++,r+=4)Pe[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const f=Pe[p-15],g=Pe[p-2],w=me(f,7)^me(f,18)^f>>>3,m=me(g,17)^me(g,19)^g>>>10;Pe[p]=m+Pe[p-7]+w+Pe[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let p=0;p<64;p++){const f=me(a,6)^me(a,11)^me(a,25),g=d+f+jo(a,c,l)+na[p]+Pe[p]|0,m=(me(t,2)^me(t,13)^me(t,22))+Yo(t,n,i)|0;d=l,l=c,c=a,a=o+g|0,o=i,i=n,n=t,t=g+m|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,i,o,a,c,l,d)}roundClean(){Xe(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Xe(this.buffer)}}class oa extends ia{constructor(){super(32);P(this,"A",ke[0]|0);P(this,"B",ke[1]|0);P(this,"C",ke[2]|0);P(this,"D",ke[3]|0);P(this,"E",ke[4]|0);P(this,"F",ke[5]|0);P(this,"G",ke[6]|0);P(this,"H",ke[7]|0)}}const aa=ks(()=>new oa,Jo(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nr=BigInt(0),ir=BigInt(1);function Tt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Ls(s){if(typeof s=="bigint"){if(!Ct(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function Rt(s){const e=Ls(s).toString(16);return e.length&1?"0"+e:e}function Bs(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?nr:BigInt("0x"+s)}function Nt(s){return Bs(nt(s))}function Ms(s){return Bs(nt(ca(ee(s)).reverse()))}function or(s,e){ve(e),s=Ls(s);const r=It(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function $s(s,e){return or(s,e).reverse()}function ca(s){return Uint8Array.from(s)}const Ct=s=>typeof s=="bigint"&&nr<=s;function la(s,e,r){return Ct(s)&&Ct(e)&&Ct(r)&&e<=s&&s<r}function da(s,e,r,t){if(!la(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function ua(s){let e;for(e=0;s>nr;s>>=ir,e+=1);return e}const ar=s=>(ir<<BigInt(s))-ir;function ha(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=x=>new Uint8Array(x),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),d=0;const p=()=>{c.fill(1),l.fill(0),d=0},f=(...x)=>r(l,Oe(c,...x)),g=(x=n)=>{l=f(i,x),c=f(),x.length!==0&&(l=f(o,x),c=f())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let x=0;const S=[];for(;x<e;){c=f();const I=c.slice();S.push(I),x+=c.length}return Oe(...S)};return(x,S)=>{p(),g(x);let I;for(;!(I=S(w()));)g();return p(),I}}function cr(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function Us(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),oe=BigInt(1),Be=BigInt(2),Fs=BigInt(3),Ws=BigInt(4),Hs=BigInt(5),pa=BigInt(7),Gs=BigInt(8),_a=BigInt(9),Ks=BigInt(16);function _e(s,e){const r=s%e;return r>=ae?r:e+r}function ue(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function Vs(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=_e(s,e),t=e,n=ae,i=oe;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==oe)throw new Error("invert: does not exist");return _e(n,e)}function lr(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function qs(s,e){const r=(s.ORDER+oe)/Ws,t=s.pow(e,r);return lr(s,t,e),t}function fa(s,e){const r=(s.ORDER-Hs)/Gs,t=s.mul(e,Be),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Be),n),a=s.mul(i,s.sub(o,s.ONE));return lr(s,a,e),a}function ga(s){const e=Ot(s),r=zs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+pa)/Ks;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,t);const p=a.mul(l,n),f=a.mul(l,i),g=a.eql(a.sqr(d),c),w=a.eql(a.sqr(p),c);l=a.cmov(l,d,g),d=a.cmov(f,p,w);const m=a.eql(a.sqr(d),c),x=a.cmov(l,d,m);return lr(a,x,c),x}}function zs(s){if(s<Fs)throw new Error("sqrt is not defined for small field");let e=s-oe,r=0;for(;e%Be===ae;)e/=Be,r++;let t=Be;const n=Ot(s);for(;js(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return qs;let i=n.pow(t,e);const o=(e+oe)/Be;return function(c,l){if(c.is0(l))return l;if(js(c,l)!==1)throw new Error("Cannot find square root");let d=r,p=c.mul(c.ONE,i),f=c.pow(l,e),g=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let w=1,m=c.sqr(f);for(;!c.eql(m,c.ONE);)if(w++,m=c.sqr(m),w===d)throw new Error("Cannot find square root");const x=oe<<BigInt(d-w-1),S=c.pow(p,x);d=w,p=c.sqr(S),f=c.mul(f,p),g=c.mul(g,S)}return g}}function xa(s){return s%Ws===Fs?qs:s%Gs===Hs?fa:s%Ks===_a?ga(s):zs(s)}const wa=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ma(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=wa.reduce((t,n)=>(t[n]="function",t),e);return cr(s,r),s}function ya(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===oe)return e;let t=s.ONE,n=e;for(;r>ae;)r&oe&&(t=s.mul(t,n)),n=s.sqr(n),r>>=oe;return t}function Js(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function js(s,e){const r=(s.ORDER-oe)/Be,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function ba(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Sa{constructor(e,r={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ae);P(this,"ONE",oe);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=ba(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return _e(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&oe)===oe}neg(e){return _e(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return _e(e*e,this.ORDER)}add(e,r){return _e(e+r,this.ORDER)}sub(e,r){return _e(e-r,this.ORDER)}mul(e,r){return _e(e*r,this.ORDER)}pow(e,r){return ya(this,e,r)}div(e,r){return _e(e*Vs(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Vs(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=xa(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?$s(e,this.BYTES):or(e,this.BYTES)}fromBytes(e,r=!1){ee(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Ms(e):Nt(e);if(a&&(c=_e(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Js(this,e)}cmov(e,r,t){return t?r:e}}function Ot(s,e={}){return new Sa(s,e)}function Ys(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function Xs(s){const e=Ys(s);return e+Math.ceil(e/2)}function va(s,e,r=!1){ee(s);const t=s.length,n=Ys(e),i=Xs(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?Ms(s):Nt(s),a=_e(o,e-oe)+oe;return r?$s(a,n):or(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ze=BigInt(0),Me=BigInt(1);function kt(s,e){const r=e.negate();return s?r:e}function Zs(s,e){const r=Js(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function Qs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function dr(s,e){Qs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=ar(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function en(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=Me);const l=e*t,d=l+Math.abs(a)-1,p=a===0,f=a<0,g=e%2!==0;return{nextN:c,offset:d,isZero:p,isNeg:f,isNegF:g,offsetF:l}}const ur=new WeakMap,tn=new WeakMap;function hr(s){return tn.get(s)||1}function rn(s){if(s!==Ze)throw new Error("invalid wNAF")}class Ea{constructor(e,r){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ze;)r&Me&&(t=t.add(n)),n=n.double(),r>>=Me;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=dr(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=dr(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:p,isNegF:f,offsetF:g}=en(t,a,o);t=c,d?i=i.add(kt(f,r[g])):n=n.add(kt(p,r[l]))}return rn(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=dr(e,this.bits);for(let o=0;o<i.windows&&t!==Ze;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=en(t,o,i);if(t=a,!l){const p=r[c];n=n.add(d?p.negate():p)}}return rn(t),n}getPrecomputes(e,r,t){let n=ur.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),ur.set(r,n))),n}cached(e,r,t){const n=hr(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=hr(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){Qs(r,this.bits),tn.set(e,r),ur.delete(e)}hasCache(e){return hr(e)!==1}}function Ia(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ze||t>Ze;)r&Me&&(i=i.add(n)),t&Me&&(o=o.add(n)),n=n.double(),r>>=Me,t>>=Me;return{p1:i,p2:o}}function sn(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ma(e),e}else return Ot(s,{isLE:r})}function Aa(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ze))throw new Error(`CURVE.${c} must be positive bigint`)}const n=sn(e.p,r.Fp,t),i=sn(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Ta(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class nn{constructor(e,r){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(Ts(e),ee(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Xe(n)}update(e){return Ye(this),this.iHash.update(e),this}digestInto(e){Ye(this),ee(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const on=(s,e,r)=>new nn(s,e).update(r).digest();on.create=(s,e)=>new nn(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const an=(s,e)=>(s+(s>=0?e:-e)/cn)/e;function Ra(s,e,r){const[[t,n],[i,o]]=e,a=an(o*s,r),c=an(-n*s,r);let l=s-a*t-c*i,d=-a*n-c*o;const p=l<Ie,f=d<Ie;p&&(l=-l),f&&(d=-d);const g=ar(Math.ceil(ua(r)/2))+Qe;if(l<Ie||l>=g||d<Ie||d>=g)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:f,k2:d}}function pr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function _r(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return Tt(r.lowS,"lowS"),Tt(r.prehash,"prehash"),r.format!==void 0&&pr(r.format),r}class Na extends Error{constructor(e=""){super(e)}}const De={Err:Na,_tlv:{encode:(s,e)=>{const{Err:r}=De;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=Rt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?Rt(n.length/2|128):"";return Rt(s)+i+n+e},decode(s,e){const{Err:r}=De;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=De;if(s<Ie)throw new e("integer: negative integers are not allowed");let r=Rt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=De;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Nt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=De,n=ee(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=De,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Qe=BigInt(1),cn=BigInt(2),Pt=BigInt(3),Ca=BigInt(4);function Oa(s,e={}){const r=Aa("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;cr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=dn(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(W,y,b){const{x:R,y:O}=y.toAffine(),$=t.toBytes(R);if(Tt(b,"isCompressed"),b){d();const B=!t.isOdd(O);return Oe(ln(B),$)}else return Oe(Uint8Array.of(4),$,t.toBytes(O))}function f(W){ee(W,void 0,"Point");const{publicKey:y,publicKeyUncompressed:b}=l,R=W.length,O=W[0],$=W.subarray(1);if(R===y&&(O===2||O===3)){const B=t.fromBytes($);if(!t.isValid(B))throw new Error("bad point: is not on curve, wrong x");const M=m(B);let k;try{k=t.sqrt(M)}catch(A){const N=A instanceof Error?": "+A.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}d();const V=t.isOdd(k);return(O&1)===1!==V&&(k=t.neg(k)),{x:B,y:k}}else if(R===b&&O===4){const B=t.BYTES,M=t.fromBytes($.subarray(0,B)),k=t.fromBytes($.subarray(B,B*2));if(!x(M,k))throw new Error("bad point: is not on curve");return{x:M,y:k}}else throw new Error(`bad point: got length ${R}, expected compressed=${y} or uncompressed=${b}`)}const g=e.toBytes||p,w=e.fromBytes||f;function m(W){const y=t.sqr(W),b=t.mul(y,W);return t.add(t.add(b,t.mul(W,i.a)),i.b)}function x(W,y){const b=t.sqr(y),R=m(W);return t.eql(b,R)}if(!x(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const S=t.mul(t.pow(i.a,Pt),Ca),I=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(S,I)))throw new Error("bad curve params: a or b");function U(W,y,b=!1){if(!t.isValid(y)||b&&t.is0(y))throw new Error(`bad point coordinate ${W}`);return y}function C(W){if(!(W instanceof z))throw new Error("Weierstrass Point expected")}function L(W){if(!c||!c.basises)throw new Error("no endo");return Ra(W,c.basises,n.ORDER)}const H=Us((W,y)=>{const{X:b,Y:R,Z:O}=W;if(t.eql(O,t.ONE))return{x:b,y:R};const $=W.is0();y==null&&(y=$?t.ONE:t.inv(O));const B=t.mul(b,y),M=t.mul(R,y),k=t.mul(O,y);if($)return{x:t.ZERO,y:t.ZERO};if(!t.eql(k,t.ONE))throw new Error("invZ was invalid");return{x:B,y:M}}),G=Us(W=>{if(W.is0()){if(e.allowInfinityPoint&&!t.is0(W.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:b}=W.toAffine();if(!t.isValid(y)||!t.isValid(b))throw new Error("bad point: x or y not field elements");if(!x(y,b))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function q(W,y,b,R,O){return b=new z(t.mul(b.X,W),b.Y,b.Z),y=kt(R,y),b=kt(O,b),y.add(b)}const F=class F{constructor(y,b,R){P(this,"X");P(this,"Y");P(this,"Z");this.X=U("x",y),this.Y=U("y",b,!0),this.Z=U("z",R),Object.freeze(this)}static CURVE(){return i}static fromAffine(y){const{x:b,y:R}=y||{};if(!y||!t.isValid(b)||!t.isValid(R))throw new Error("invalid affine point");if(y instanceof F)throw new Error("projective point not allowed");return t.is0(b)&&t.is0(R)?F.ZERO:new F(b,R,t.ONE)}static fromBytes(y){const b=F.fromAffine(w(ee(y,void 0,"point")));return b.assertValidity(),b}static fromHex(y){return F.fromBytes(It(y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,b=!0){return D.createCache(this,y),b||this.multiply(Pt),this}assertValidity(){G(this)}hasEvenY(){const{y}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(y)}equals(y){C(y);const{X:b,Y:R,Z:O}=this,{X:$,Y:B,Z:M}=y,k=t.eql(t.mul(b,M),t.mul($,O)),V=t.eql(t.mul(R,M),t.mul(B,O));return k&&V}negate(){return new F(this.X,t.neg(this.Y),this.Z)}double(){const{a:y,b}=i,R=t.mul(b,Pt),{X:O,Y:$,Z:B}=this;let M=t.ZERO,k=t.ZERO,V=t.ZERO,E=t.mul(O,O),A=t.mul($,$),N=t.mul(B,B),T=t.mul(O,$);return T=t.add(T,T),V=t.mul(O,B),V=t.add(V,V),M=t.mul(y,V),k=t.mul(R,N),k=t.add(M,k),M=t.sub(A,k),k=t.add(A,k),k=t.mul(M,k),M=t.mul(T,M),V=t.mul(R,V),N=t.mul(y,N),T=t.sub(E,N),T=t.mul(y,T),T=t.add(T,V),V=t.add(E,E),E=t.add(V,E),E=t.add(E,N),E=t.mul(E,T),k=t.add(k,E),N=t.mul($,B),N=t.add(N,N),E=t.mul(N,T),M=t.sub(M,E),V=t.mul(N,A),V=t.add(V,V),V=t.add(V,V),new F(M,k,V)}add(y){C(y);const{X:b,Y:R,Z:O}=this,{X:$,Y:B,Z:M}=y;let k=t.ZERO,V=t.ZERO,E=t.ZERO;const A=i.a,N=t.mul(i.b,Pt);let T=t.mul(b,$),K=t.mul(R,B),J=t.mul(O,M),Z=t.add(b,R),j=t.add($,B);Z=t.mul(Z,j),j=t.add(T,K),Z=t.sub(Z,j),j=t.add(b,O);let Q=t.add($,M);return j=t.mul(j,Q),Q=t.add(T,J),j=t.sub(j,Q),Q=t.add(R,O),k=t.add(B,M),Q=t.mul(Q,k),k=t.add(K,J),Q=t.sub(Q,k),E=t.mul(A,j),k=t.mul(N,J),E=t.add(k,E),k=t.sub(K,E),E=t.add(K,E),V=t.mul(k,E),K=t.add(T,T),K=t.add(K,T),J=t.mul(A,J),j=t.mul(N,j),K=t.add(K,J),J=t.sub(T,J),J=t.mul(A,J),j=t.add(j,J),T=t.mul(K,j),V=t.add(V,T),T=t.mul(Q,j),k=t.mul(Z,k),k=t.sub(k,T),T=t.mul(Z,K),E=t.mul(Q,E),E=t.add(E,T),new F(k,V,E)}subtract(y){return this.add(y.negate())}is0(){return this.equals(F.ZERO)}multiply(y){const{endo:b}=e;if(!n.isValidNot0(y))throw new Error("invalid scalar: out of range");let R,O;const $=B=>D.cached(this,B,M=>Zs(F,M));if(b){const{k1neg:B,k1:M,k2neg:k,k2:V}=L(y),{p:E,f:A}=$(M),{p:N,f:T}=$(V);O=A.add(T),R=q(b.beta,E,N,B,k)}else{const{p:B,f:M}=$(y);R=B,O=M}return Zs(F,[R,O])[0]}multiplyUnsafe(y){const{endo:b}=e,R=this;if(!n.isValid(y))throw new Error("invalid scalar: out of range");if(y===Ie||R.is0())return F.ZERO;if(y===Qe)return R;if(D.hasCache(this))return this.multiply(y);if(b){const{k1neg:O,k1:$,k2neg:B,k2:M}=L(y),{p1:k,p2:V}=Ia(F,R,$,M);return q(b.beta,k,V,O,B)}else return D.unsafe(R,y)}toAffine(y){return H(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Qe?!0:y?y(F,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Qe?this:y?y(F,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return Tt(y,"isCompressed"),this.assertValidity(),g(F,this,y)}toHex(y=!0){return nt(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(F,"BASE",new F(i.Gx,i.Gy,t.ONE)),P(F,"ZERO",new F(t.ZERO,t.ONE,t.ZERO)),P(F,"Fp",t),P(F,"Fn",n);let z=F;const ne=n.BITS,D=new Ea(z,e.endo?Math.ceil(ne/2):ne);return z.BASE.precompute(8),z}function ln(s){return Uint8Array.of(s?2:3)}function dn(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ka(s,e={}){const{Fn:r}=s,t=e.randomBytes||Ps,n=Object.assign(dn(s.Fp,r),{seed:Xs(r.ORDER)});function i(g){try{const w=r.fromBytes(g);return r.isValidNot0(w)}catch{return!1}}function o(g,w){const{publicKey:m,publicKeyUncompressed:x}=n;try{const S=g.length;return w===!0&&S!==m||w===!1&&S!==x?!1:!!s.fromBytes(g)}catch{return!1}}function a(g=t(n.seed)){return va(ee(g,n.seed,"seed"),r.ORDER)}function c(g,w=!0){return s.BASE.multiply(r.fromBytes(g)).toBytes(w)}function l(g){const{secretKey:w,publicKey:m,publicKeyUncompressed:x}=n;if(!rr(g)||"_lengths"in r&&r._lengths||w===m)return;const S=ee(g,void 0,"key").length;return S===m||S===x}function d(g,w,m=!0){if(l(g)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const x=r.fromBytes(g);return s.fromBytes(w).multiply(x).toBytes(m)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},f=Ta(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:f,Point:s,utils:p,lengths:n})}function Pa(s,e,r={}){Ts(e),cr(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Ps,n=r.hmac||((y,b)=>on(e,y,b)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:p,utils:f,lengths:g}=ka(s,r),w={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},m=a*cn<i.ORDER;function x(y){const b=a>>Qe;return y>b}function S(y,b){if(!o.isValidNot0(b))throw new Error(`invalid signature ${y}: out of range 1..Point.Fn.ORDER`);return b}function I(){if(m)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(y,b){pr(b);const R=g.signature,O=b==="compact"?R:b==="recovered"?R+1:void 0;return ee(y,O)}class C{constructor(b,R,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=S("r",b),this.s=S("s",R),O!=null){if(I(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(b,R=w.format){U(b,R);let O;if(R==="der"){const{r:k,s:V}=De.toSig(ee(b));return new C(k,V)}R==="recovered"&&(O=b[0],R="compact",b=b.subarray(1));const $=g.signature/2,B=b.subarray(0,$),M=b.subarray($,$*2);return new C(o.fromBytes(B),o.fromBytes(M),O)}static fromHex(b,R){return this.fromBytes(It(b),R)}assertRecovery(){const{recovery:b}=this;if(b==null)throw new Error("invalid recovery id: must be present");return b}addRecoveryBit(b){return new C(this.r,this.s,b)}recoverPublicKey(b){const{r:R,s:O}=this,$=this.assertRecovery(),B=$===2||$===3?R+a:R;if(!i.isValid(B))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes(B),k=s.fromBytes(Oe(ln(($&1)===0),M)),V=o.inv(B),E=H(ee(b,void 0,"msgHash")),A=o.create(-E*V),N=o.create(O*V),T=s.BASE.multiplyUnsafe(A).add(k.multiplyUnsafe(N));if(T.is0())throw new Error("invalid recovery: point at infinify");return T.assertValidity(),T}hasHighS(){return x(this.s)}toBytes(b=w.format){if(pr(b),b==="der")return It(De.hexFromSig(this));const{r:R,s:O}=this,$=o.toBytes(R),B=o.toBytes(O);return b==="recovered"?(I(),Oe(Uint8Array.of(this.assertRecovery()),$,B)):Oe($,B)}toHex(b){return nt(this.toBytes(b))}}const L=r.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const R=Nt(b),O=b.length*8-c;return O>0?R>>BigInt(O):R},H=r.bits2int_modN||function(b){return o.create(L(b))},G=ar(c);function q(y){return da("num < 2^"+c,y,Ie,G),o.toBytes(y)}function z(y,b){return ee(y,void 0,"message"),b?ee(e(y),void 0,"prehashed message"):y}function ne(y,b,R){const{lowS:O,prehash:$,extraEntropy:B}=_r(R,w);y=z(y,$);const M=H(y),k=o.fromBytes(b);if(!o.isValidNot0(k))throw new Error("invalid private key");const V=[q(k),q(M)];if(B!=null&&B!==!1){const T=B===!0?t(g.secretKey):B;V.push(ee(T,void 0,"extraEntropy"))}const E=Oe(...V),A=M;function N(T){const K=L(T);if(!o.isValidNot0(K))return;const J=o.inv(K),Z=s.BASE.multiply(K).toAffine(),j=o.create(Z.x);if(j===Ie)return;const Q=o.create(J*o.create(A+j*k));if(Q===Ie)return;let Fe=(Z.x===j?0:2)|Number(Z.y&Qe),Wn=Q;return O&&x(Q)&&(Wn=o.neg(Q),Fe^=1),new C(j,Wn,m?void 0:Fe)}return{seed:E,k2sig:N}}function D(y,b,R={}){const{seed:O,k2sig:$}=ne(y,b,R);return ha(e.outputLen,o.BYTES,n)(O,$).toBytes(R.format)}function F(y,b,R,O={}){const{lowS:$,prehash:B,format:M}=_r(O,w);if(R=ee(R,void 0,"publicKey"),b=z(b,B),!rr(y)){const k=y instanceof C?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+k)}U(y,M);try{const k=C.fromBytes(y,M),V=s.fromBytes(R);if($&&k.hasHighS())return!1;const{r:E,s:A}=k,N=H(b),T=o.inv(A),K=o.create(N*T),J=o.create(E*T),Z=s.BASE.multiplyUnsafe(K).add(V.multiplyUnsafe(J));return Z.is0()?!1:o.create(Z.x)===E}catch{return!1}}function W(y,b,R={}){const{prehash:O}=_r(R,w);return b=z(b,O),C.fromBytes(y,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:p,utils:f,lengths:g,Point:s,sign:D,verify:F,recoverPublicKey:W,Signature:C,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Da={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},un=BigInt(2);function La(s){const e=fr.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,d=l*l*s%e,p=ue(d,r,e)*d%e,f=ue(p,r,e)*d%e,g=ue(f,un,e)*l%e,w=ue(g,n,e)*g%e,m=ue(w,i,e)*w%e,x=ue(m,a,e)*m%e,S=ue(x,c,e)*x%e,I=ue(S,a,e)*m%e,U=ue(I,r,e)*d%e,C=ue(U,o,e)*w%e,L=ue(C,t,e)*l%e,H=ue(L,un,e);if(!gr.eql(gr.sqr(H),s))throw new Error("Cannot find square root");return H}const gr=Ot(fr.p,{sqrt:La}),Ba=Pa(Oa(fr,{Fp:gr,endo:Da}),aa),Ma=BigInt(0),it=BigInt(1),$a=BigInt(2),Ua=BigInt(7),Fa=BigInt(256),Wa=BigInt(113),hn=[],pn=[],_n=[];for(let s=0,e=it,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],hn.push(2*(5*t+r)),pn.push((s+1)*(s+2)/2%64);let n=Ma;for(let i=0;i<7;i++)e=(e<<it^(e>>Ua)*Wa)%Fa,e&$a&&(n^=it<<(it<<BigInt(i))-it);_n.push(n)}const fn=Qo(_n,!0),Ha=fn[0],Ga=fn[1],gn=(s,e,r)=>r>32?ra(s,e,r):ea(s,e,r),xn=(s,e,r)=>r>32?sa(s,e,r):ta(s,e,r);function Ka(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],d=r[c+1],p=gn(l,d,1)^r[a],f=xn(l,d,1)^r[a+1];for(let g=0;g<50;g+=10)s[o+g]^=p,s[o+g+1]^=f}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=pn[o],c=gn(n,i,a),l=xn(n,i,a),d=hn[o];n=s[d],i=s[d+1],s[d]=c,s[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Ha[t],s[1]^=Ga[t]}Xe(r)}class xr{constructor(e,r,t,n=!1,i=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Go(this.state)}clone(){return this._cloneInto()}keccak(){Ns(this.state32),Ka(this.state32,this.rounds),Ns(this.state32),this.posOut=0,this.pos=0}update(e){Ye(this),ee(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,(r&128)!==0&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ye(this,!1),ee(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rs(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Xe(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new xr(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const wn=((s,e,r,t={})=>ks(()=>new xr(e,s,r),t))(1,136,32),Va=60;class qa{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Fo(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Va<n)return u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Oo(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};u.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ho(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
7
- ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=wn(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=za(a),l=c.slice(0,32),d=c.slice(32,64),p=c[64],f=p>=27?p-27:p,m=new Ba.Signature(mn(l),mn(d)).addRecoveryBit(f).recoverPublicKey(o).toBytes(!1).slice(1),x=wn(m);return"0x"+nt(x.slice(12))}}function za(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function mn(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Ja=5e3;class ja{constructor(e,r){this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyInFlight=null,this.keyFailedAt=0,this.required=!1,this.adapterConfig=e,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async seal(e){if(!e)return e;const r=this.required;if(!r&&this.hasFreshFailure())return e;try{const{version:t,key:n}=await this.currentKey(),i=await Ya(n,e);return`${t}.${Xa(i)}`}catch(t){if(r)throw this.keyFailedAt=Date.now(),t instanceof _?t:new _(h.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(t)});return this.keyFailedAt=Date.now(),u.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(Br/1e3)}초 후 재확인)`),e}}invalidate(){u.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(u.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.currentKey().then(()=>{},()=>{})}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<Br}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<Jn?{version:this.cachedVersion,key:this.cachedKey}:this.keyInFlight?this.keyInFlight:(this.keyInFlight=this.fetchAndImportKey().then(e=>(this.cachedVersion=e.version,this.cachedKey=e.key,this.cachedAt=Date.now(),this.keyFailedAt=0,u.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=yn();if(!e)throw new _(h.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다. HTTPS 환경에서 다시 시도해 주세요.");const r=await this.transport.request({url:`${this.baseUrl}/pin-key`,method:"GET",headers:{"X-Project-Id":this.adapterConfig.projectId},timeoutMs:Ja}),t=tc(r.data);if(!(t!=null&&t.keyVersion)||!(t!=null&&t.publicKey))throw new _(h.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const n=Qa(t.publicKey),i=await e.importKey("spki",ec(n),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:t.keyVersion,key:i}}}async function Ya(s,e){const r=yn();if(!r)throw new _(h.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const t=await r.encrypt({name:"RSA-OAEP"},s,new TextEncoder().encode(e));return new Uint8Array(t)}function yn(){const s=globalThis.crypto;return(s==null?void 0:s.subtle)??null}function Xa(s){return Za(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const ot="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Za(s){let e="";for(let r=0;r<s.length;r+=3){const t=s[r],n=s[r+1],i=s[r+2];e+=ot[t>>2],e+=ot[(t&3)<<4|(n??0)>>4],e+=n===void 0?"=":ot[(n&15)<<2|(i??0)>>6],e+=i===void 0?"=":ot[i&63]}return e}function Qa(s){const e=s.replace(/-----BEGIN [A-Z ]+-----/g,"").replace(/-----END [A-Z ]+-----/g,"").replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),r=e.length%4===0?e:e+"=".repeat(4-e.length%4),t=[];for(let n=0;n<r.length;n+=4){const i=[0,1,2,3].map(o=>{const a=r[n+o];if(a==="="||a===void 0)return-1;const c=ot.indexOf(a);if(c===-1)throw new _(h.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return c});t.push((i[0]&63)<<2|(i[1]&63)>>4),i[2]!==-1&&t.push((i[1]&15)<<4|(i[2]&63)>>2),i[3]!==-1&&t.push((i[2]&3)<<6|i[3]&63)}return new Uint8Array(t)}function ec(s){const e=new Uint8Array(s.length);return e.set(s),e.buffer}function tc(s){if(!s||typeof s!="object")return null;const e=s;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new _(h.PIN_ENCRYPTION_FAILED,`pin-key 조회 실패 (${e.code}): ${String(e.message??e.data??"")}`);const r=e.data;if(r&&typeof r=="object")return r}return typeof e.keyVersion=="string"&&typeof e.publicKey=="string"?e:null}const rc=3e4,sc=1e3;class nc{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,sc*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??rc);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}function ic(s){const e={raw:s},r=s.search(/(^|;)\s*info=/i),t=r>=0?s.slice(0,r):s;if(r>=0){const n=s.slice(r).replace(/^;?\s*info=/i,"").trim();n&&(e.infoUrl=n)}for(const n of t.split(";")){const[i,...o]=n.split("=");if((i==null?void 0:i.trim().toLowerCase())==="sunset"){const a=o.join("=").trim();a&&(e.sunset=a)}}return e}function bn(s){try{return new URL(s).origin}catch{return null}}class oc{constructor(e,r){this.inner=e,this.options=r}async request(e){if(!this.isGateway(e.url))return this.inner.request(e);const r=await this.inner.request(this.options.sendVersionHeader===!1?e:{...e,headers:{...e.headers,[jn]:this.options.version}});return this.inspect(r),r}isGateway(e){const r=bn(e);return r===null?!1:this.options.getGatewayBaseUrls().some(t=>bn(t)===r)}inspect(e){var n,i,o,a;const r=ac(e.headers,Xn);r&&((i=(n=this.options).onDeprecation)==null||i.call(n,ic(r)));const t=e.data;t&&t.code===ht&&((a=(o=this.options).onUnsupported)==null||a.call(o,{message:typeof t.message=="string"?t.message:void 0}))}}function ac(s,e){if(!s)return;const r=e.toLowerCase();for(const[t,n]of Object.entries(s))if(t.toLowerCase()===r&&n)return n}const cc=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function wr(){return typeof window>"u"?void 0:window}function lc(){const s=wr();return s==null?void 0:s.__crossx}function dc(s){return s==="ios"||s==="android"?s:null}function mr(){const s=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(s)?"android":/iPhone|iPad|iPod|Macintosh/i.test(s)?"ios":null}function uc(s,e){const r=o=>o.split(/[^\d]+/).filter(a=>a!=="").map(a=>Number.parseInt(a,10)),t=r(s),n=r(e),i=Math.max(t.length,n.length);for(let o=0;o<i;o+=1){const a=(t[o]??0)-(n[o]??0);if(a!==0)return a}return 0}function hc(){const s=wr();if(!s)return!1;const e=s.__crossxRNBridge;return e!=null&&e.isInstalled?!0:s.__CROSSX_BRIDGE_INITIALIZED__===!0||s.__CROSSX_RN_BRIDGE_READY__===!0}function Sn(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of cc){const r=e.exec(s);if(r)return r[1]??null}}function at(){const s=lc();if(s!=null&&s.browser)return{version:s.version??null,platform:dc(s.platform)??mr(),detectedBy:"marker"};if(hc())return{version:Sn()??null,platform:mr(),detectedBy:"bridge"};const e=Sn();return e!==void 0?{version:e,platform:mr(),detectedBy:"user-agent"}:null}function pc(){return at()!==null}function _c(s=3e3){const e=at();return e?Promise.resolve(e):wr()?new Promise(r=>{const t=Date.now(),n=setInterval(()=>{const i=at();if(i){clearInterval(n),r(i);return}Date.now()-t>=s&&(clearInterval(n),r(null))},50)}):Promise.resolve(null)}const fc=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io","https://one-wallet-oauth.onechain.nexus","https://stg-one-wallet-oauth.onechain.nexus","https://dev-one-wallet-oauth.onechain.nexus"]),gc="crossx://oauth-callback",xc="2.3.2";function wc(s){return s.platform!=="ios"?!1:s.version?uc(s.version,xc)<=0:!0}class $e{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const r=this.abortPending;r&&(u.log("[CROSSx] OAuth 대기 중단 —",e),r(e))}static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=$e.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){u.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await $e.sha256Hex(r);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=$e.generateRandom16Hex(),l=$e.generateRandom16Hex(),d=at();let p=e.authUrl;d&&e.legacyAuthUrl&&wc(d)&&(p=e.legacyAuthUrl,u.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:d.version??"(unknown)",detectedBy:d.detectedBy,authUrlBase:e.legacyAuthUrl}));const f=p.includes("?")?"&":"?",g=encodeURIComponent(window.location.origin);let w=`${p}${f}state=${c}&nonce=${l}&origin=${g}`;d&&!w.includes("redirectUrl=")&&(w+=`&redirectUrl=${encodeURIComponent(gc)}`,u.info("[CROSSx] 지갑 인앱 브라우저 감지 — redirectUrl 콜백 자동 부착",{detectedBy:d.detectedBy,appVersion:d.version??"(unknown)",platform:d.platform??"(unknown)"})),u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:p});const m=window.open(w,d?"_blank":"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!m){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const x=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),G(),t(new Error("Authentication timeout"))},300*1e3),S=10,I=30;let U=0,C=null;const L=()=>{clearInterval(H),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+I+"초간 대기합니다"),C=setTimeout(()=>{G(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},I*1e3)},H=setInterval(()=>{U++;try{if(!m.closed)return;if(!!d){G(),t(new _(h.USER_REJECTED,"로그인이 취소되었습니다"));return}const ne=typeof document<"u"&&document.hasFocus();U<=S&&!ne?L():(G(),t(new _(h.USER_REJECTED,"로그인이 취소되었습니다")))}catch{L()}},1e3),G=()=>{this.abortPending=null,clearTimeout(x),clearInterval(H),C&&clearTimeout(C),window.removeEventListener("message",q)},q=z=>{if(!fc.has(z.origin))return;G();const ne=typeof z.data.status=="string",D=ne?z.data.data??{}:z.data;u.log("[CROSSx] OAuth postMessage 수신 —",{format:ne?"wrapped":"flat",status:ne?z.data.status:"(flat)"});const F=(D==null?void 0:D.state)??z.data.state;if(!F||F!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ne&&z.data.status!=="success"){u.error("[CROSSx] OAuth 실패:",D==null?void 0:D.error),t(new Error((D==null?void 0:D.error)||"Authentication failed"));return}if(!ne&&(D!=null&&D.error)){u.error("[CROSSx] OAuth 실패:",D.error),t(new Error(D.error||"Authentication failed"));return}const W=D==null?void 0:D.idToken,y=D==null?void 0:D.accessToken,b=y??W,R=(D==null?void 0:D.email)||void 0;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!y,hasIdToken:!!W,hasEmail:!!R}),!b){u.error("[CROSSx] 토큰을 찾을 수 없음:",z.data),t(new Error("Token not found in response"));return}const O={token:b,email:R},$=B=>{$e.verifyIdTokenNonce(B,l).then(()=>r(O)).catch(M=>{u.error("[CROSSx] nonce 검증 실패:",M),t(M instanceof Error?M:new Error("nonce verification failed"))})};y?y.split(".").length===3?$(y):W?$(W):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(O)):W?$(W):t(new Error("Token not found in response"))};this.abortPending=z=>{G(),t(new Error(z))},window.addEventListener("message",q)})}}const ct="crossx_wallet_data",et="crossx_mock_pin_hash";class mc{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(ct)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(ct);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ct,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(et,i),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new _(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(ct);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return u.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return u.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){u.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return u.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(et);return r&&r!==e?!1:(r||await this.storage.set(et,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new _(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(et);if(n&&t&&n!==t)throw new _(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(et,r),u.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(u.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new _(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new _(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ct,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(et,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}const yc=["password","newPassword","recoveryPin"];class Ue{constructor(e,r,t,n,i,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null,this.pinEncryptor=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Lr))return e;const r=!e||this.tokenStore.isExpiringSoon(Lr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return u.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(u.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async sealPinFields(e){if(!this.pinEncryptor||!e||typeof e!="object")return e;let r=null;for(const t of yc){const n=e[t];if(typeof n!="string"||n==="")continue;const i=await this.pinEncryptor.seal(n);i!==n&&(r||(r={...e}),r[t]=i)}return r??e}async request(e,r,t,n=!1,i=!1){var d,p,f,g;const o=await this.ensureValidToken(),a=`${this.baseUrl}${r}`,c={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId},l=await this.sealPinFields(t);try{const m=(await this.transport.request({url:a,method:e,headers:c,body:l??void 0})).data;if(m&&typeof m.code=="number"){if(m.code<0||m.code>=400){const x=m.message||m.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:m.code,message:x,url:a,method:e});const S=Ue.mapGatewayError(m.code,m.data);if(S===h.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!i))return u.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,r,t,n,!0);if(S===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(u.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0,i);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(S===h.USER_NOT_FOUND)throw u.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(d=this._onUnauthorized)==null||d.call(this),new _(h.USER_NOT_FOUND,Ue.getGatewayErrorMessage(m.code,x));const I=S===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:S,U=I===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ue.getGatewayErrorMessage(m.code,x),C=m.data;let L;throw S===h.PIN_LOCKED?L=Ue.extractLockDetails(C):S===h.ADDRESS_LIMIT_EXCEEDED?L={limit:dt,raw:C}:L=C??void 0,new _(I,U,L)}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:m.code,url:a,method:e}),m.data??m}return m}catch(w){if(w instanceof _)throw w;const m=((p=w.response)==null?void 0:p.status)??w.status;if((m===401||m===403)&&!n&&this._onTokenRefresh){if(u.warn(`[CROSSx] HTTP ${m} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0,i);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((f=w.response)!=null&&f.data){const x=w.response.data,S=x.message||x.data||"API 요청에 실패했습니다",I=x.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:I,message:S,url:a,method:e,status:(g=w.response)==null?void 0:g.status}),new _(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${I}): ${S}`)}throw w}}async checkWallet(){var r,t;u.log("[CROSSx] GET /mnemonic/check"),(t=(r=this.pinEncryptor)==null?void 0:r.prewarm)==null||t.call(r);const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(h.MIGRATION_BACKUP_EXISTS,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new _(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new _(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new _(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new _(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new _(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new _(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new _(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case ht:return h.SDK_VERSION_UNSUPPORTED;case-10028:return Ue.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10045:return h.PIN_ENCRYPTION_INVALID;case-10046:return h.PIN_POLICY_VIOLATION;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case ht:return`This SDK version is no longer supported. Update @nexus-cross/crossx-sdk-core.${r?` (${r})`:""}`;case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${dt} accounts allowed.`;case-10045:return"Could not securely send your PIN. Please try again.";case-10046:return r||"This PIN does not meet the security policy. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class bc{constructor(e,r,t,n=()=>{},i=()=>{},o=()=>{}){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,this.assertBridgeSessionActive=n,this.getAppName=i,this.onBridgeUnauthorized=o,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(a,c)=>e.prepare(a,c)),e.migrateWallet&&(this.migrateWallet=(a,c)=>e.migrateWallet(a,c)),e.verifyPin&&(this.verifyPin=a=>e.verifyPin(a)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(a,c)=>e.verifyRecoveryPin(a,c))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async innerOwnsAddress(e,r){if(!r)return!0;try{return(await this.inner.getAddresses(e)).some(n=>n.address.toLowerCase()===r.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,r,t,n){return!Ur(e)||!await this.innerOwnsAddress(r,t)?!1:(this.onBridgeUnauthorized(`native 가 ${n} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){this.assertBridgeSessionActive();try{const c=await a.signMessage({chainId:r,message:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,o,"signMessage"))throw He(c,h.SIGNATURE_FAILED)}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){this.assertBridgeSessionActive();try{const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n,dappName:this.getAppName()});return{chainId:r,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,o,"signTypedData"))throw He(c,h.SIGNATURE_FAILED)}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){this.assertBridgeSessionActive();try{const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n,dappName:this.getAppName()});return{chainId:r,signature:a.signedTx,format:"hex"}}catch(a){if(!await this.recoverFromUnauthorized(a,e,t.from,"signTransaction"))throw He(a,h.SIGNATURE_FAILED)}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,dappName:this.getAppName()})).txHash}}catch(o){if(!await this.recoverFromUnauthorized(o,e,t.from,"sendTransaction"))throw He(o,h.TRANSACTION_FAILED)}}if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class lt{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){return this.isCacheValid()?Array.from(this.cache.values()):this._fetchPromise?this._fetchPromise:(this._fetchPromise=this._doFetchChains().finally(()=>{this._fetchPromise=null}),this._fetchPromise)}async _doFetchChains(){try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=lt.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?zn:qn;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new _(lt.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=lt.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new _(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(_t).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;case ht:return h.SDK_VERSION_UNSUPPORTED;default:return h.UNKNOWN_ERROR}}}const yr="linear(0, 0.0152, 0.0546, 0.1107, 0.1771, 0.2494, 0.3236, 0.3973, 0.4684, 0.5356, 0.598, 0.655, 0.7066, 0.7526, 0.7933, 0.829, 0.8599, 0.8865, 0.9092, 0.9283, 0.9443, 0.9576, 0.9685, 0.9774, 0.9845, 0.9901, 0.9945, 0.9979, 1.0004, 1.0022, 1.0035, 1.0043, 1.0048, 1.005, 1.005, 1.0049, 1.0046, 1.0043, 1.004, 1.0036, 1.0032, 1.0029, 1.0025, 1.0022, 1.0019, 1.0016, 1.0014, 1.0011, 1.0009, 1.0008, 1.0006)",Sc=['<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:28.16%;top:32.04%;width:0.96%;height:1%;--x0:64.9347px;--y0:44.2101px;--r0:46.0deg;--x1:-14.2856px;--y1:-9.7262px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="2.65719" height="2.63854" viewBox="0 0 2.65719 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.3286 2.63854C2.06236 2.63854 2.65719 2.04788 2.65719 1.31927C2.65719 0.590657 2.06236 0 1.3286 0C0.594835 0 0 0.590657 0 1.31927C0 2.04788 0.594835 2.63854 1.3286 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:16.05%;top:64.23%;width:0.97%;height:1%;--x0:98.3418px;--y0:-41.6939px;--r0:46.0deg;--x1:-21.6352px;--y1:9.1727px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="2.65719" height="2.63854" viewBox="0 0 2.65719 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.3286 2.63854C2.06236 2.63854 2.65719 2.04788 2.65719 1.31927C2.65719 0.590657 2.06236 0 1.3286 0C0.594835 0 0 0.590657 0 1.31927C0 2.04788 0.594835 2.63854 1.3286 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:40.21%;top:23.2%;width:1.11%;height:1.15%;--x0:31.463px;--y0:67.6121px;--r0:46.0deg;--x1:-6.9219px;--y1:-14.8747px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="3.06599" height="3.04447" viewBox="0 0 3.06599 3.04447" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.53299 3.04447C2.37964 3.04447 3.06599 2.36294 3.06599 1.52223C3.06599 0.681528 2.37964 0 1.53299 0C0.686344 0 0 0.681528 0 1.52223C0 2.36294 0.686344 3.04447 1.53299 3.04447Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:67.21%;top:39.57%;width:0.96%;height:1%;--x0:-42.8544px;--y0:24.1183px;--r0:-46.0deg;--x1:9.428px;--y1:-5.306px;--r1:11.0deg"><svg preserveAspectRatio="none" width="2.65718" height="2.63854" viewBox="0 0 2.65718 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.32858 2.63854C2.06234 2.63854 2.65718 2.04789 2.65718 1.31927C2.65718 0.59066 2.06234 0 1.32858 0C0.594819 0 0 0.59066 0 1.31927C0 2.04789 0.594819 2.63854 1.32858 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:79.86%;top:71.84%;width:0.96%;height:1%;--x0:-77.7582px;--y0:-62.0034px;--r0:-46.0deg;--x1:17.1068px;--y1:13.6407px;--r1:11.0deg"><svg preserveAspectRatio="none" width="2.65718" height="2.63854" viewBox="0 0 2.65718 2.63854" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M1.32858 2.63854C2.06234 2.63854 2.65718 2.04789 2.65718 1.31927C2.65718 0.59066 2.06234 0 1.32858 0C0.594819 0 0 0.59066 0 1.31927C0 2.04789 0.594819 2.63854 1.32858 2.63854Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:23.14%;top:35.69%;width:3.75%;height:3.88%;--x0:74.93px;--y0:30.6249px;--r0:46.0deg;--x1:-16.4846px;--y1:-6.7375px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18151 10.2903L5.15086 9.91483C4.92602 7.39807 2.91268 5.39886 0.378137 5.1756L0 5.14515L0.378137 5.11471C2.91268 4.89145 4.92602 2.89225 5.15086 0.375487L5.18151 0L5.21217 0.375487C5.43701 2.89225 7.45034 4.89145 9.98489 5.11471L10.363 5.14515L9.98489 5.1756C7.45034 5.39886 5.43701 7.39807 5.21217 9.91483L5.18151 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:67.4%;top:31.51%;width:3.75%;height:3.88%;--x0:-47.219px;--y0:41.7751px;--r0:-46.0deg;--x1:10.3882px;--y1:-9.1905px;--r1:11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18151 10.2903L5.15085 9.91482C4.92601 7.39806 2.91268 5.39886 0.378133 5.1756L0 5.14515L0.378133 5.11471C2.91268 4.89145 4.92601 2.89225 5.15085 0.375487L5.18151 0L5.21217 0.375487C5.437 2.89225 7.45033 4.89145 9.98488 5.11471L10.363 5.14515L9.98488 5.1756C7.45033 5.39886 5.437 7.39806 5.21217 9.91482L5.18151 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:63.46%;top:71.24%;width:3.75%;height:3.89%;--x0:-36.3443px;--y0:-64.2541px;--r0:-46.0deg;--x1:7.9957px;--y1:14.1359px;--r1:11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18151 10.2903L5.15085 9.91482C4.92601 7.39806 2.91268 5.39886 0.378133 5.1756L0 5.14515L0.378133 5.11471C2.91268 4.89145 4.92601 2.89225 5.15085 0.375487L5.18151 0L5.21217 0.375487C5.437 2.89225 7.45033 4.89145 9.98488 5.11471L10.363 5.14515L9.98488 5.1756C7.45033 5.39886 5.437 7.39806 5.21217 9.91482L5.18151 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:72.73%;top:39.83%;width:3.76%;height:3.88%;--x0:-61.9455px;--y0:19.5786px;--r0:-46.0deg;--x1:13.628px;--y1:-4.3073px;--r1:11.0deg"><svg preserveAspectRatio="none" width="10.363" height="10.2903" viewBox="0 0 10.363 10.2903" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M5.18152 10.2903L5.15086 9.91482C4.92602 7.39806 2.9127 5.39886 0.378149 5.1756L0 5.14515L0.378149 5.1147C2.9127 4.89144 4.92602 2.89224 5.15086 0.37548L5.18152 0L5.21218 0.37548C5.43702 2.89224 7.45035 4.89144 9.9849 5.1147L10.363 5.14515L9.9849 5.1756C7.45035 5.39886 5.43702 7.39806 5.21218 9.91482L5.18152 10.2903Z" fill="white"/></svg></span>','<span class="__crossx-wc-part __crossx-wc-sparkle" style="left:43.4%;top:18.31%;width:5.63%;height:5.82%;--x0:16.4301px;--y0:74.4203px;--r0:46.0deg;--x1:-3.6146px;--y1:-16.3725px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="15.5343" height="15.4253" viewBox="0 0 15.5343 15.4253" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.76716 15.4253L6.84736 12.2185C6.34659 10.4831 4.97711 9.12326 3.2295 8.626L0 7.71266L3.2295 6.79932C4.97711 6.30205 6.34659 4.94219 6.84736 3.20684L7.76716 0L8.68696 3.20684C9.18774 4.94219 10.5572 6.30205 12.3048 6.79932L15.5343 7.71266L12.3048 8.626C10.5572 9.12326 9.18774 10.4831 8.68696 12.2185L7.76716 15.4253Z" fill="white"/></svg></span>','<span class="__crossx-wc-part" style="left:53.45%;top:13.67%;width:8.11%;height:9.28%;--x0:-14.7411px;--y0:82.1862px;--r0:-46.0deg;--x1:3.243px;--y1:-18.081px;--r1:11.0deg"><svg preserveAspectRatio="none" width="22.3793" height="24.5926" viewBox="0 0 22.3793 24.5926" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M16.7845 3.51007C21.1906 5.1057 23.1825 10.7014 21.235 16.0178C19.2875 21.3341 14.1335 24.3488 9.72748 22.7606L6.51367 21.3561L14.2816 2.52475L16.7845 3.51007Z" fill="#6D45D2"/><path d="M19.2947 14.8182C20.9983 9.42011 18.7506 3.91485 14.2744 2.52192C9.79811 1.12899 4.78832 4.37586 3.08469 9.774C1.38106 15.1721 3.62872 20.6774 8.10498 22.0703C12.5812 23.4632 17.591 20.2164 19.2947 14.8182Z" fill="#A872FF"/><path d="M12.9006 3.73181C13.3301 3.8127 13.7374 3.94505 14.1298 4.12153C13.9595 4.07006 13.7744 4.02594 13.5967 3.98917C9.82747 3.25386 6.00643 6.50394 5.07339 11.2173C4.53282 13.9453 5.08079 16.7321 6.53219 18.6881C7.21346 19.6072 8.05024 20.2984 8.99069 20.7249C7.76144 20.3572 6.6803 19.5705 5.84352 18.4307C4.39212 16.4674 3.85155 13.6732 4.38472 10.9526C5.31776 6.23188 9.14619 2.98915 12.908 3.72446L12.9006 3.73181Z" fill="#6D45D2"/><path d="M11.7916 6.49461L8.41779 8.51979C7.82275 8.87508 7.59466 9.70708 7.90998 10.3664C8.2253 11.0257 8.97184 11.2735 9.56688 10.9182L12.4206 9.2046L11.039 10.7534L10.8461 16.9886C10.8229 17.7398 11.3553 18.3699 12.0306 18.3905C12.706 18.4111 13.2763 17.8147 13.2996 17.0634L13.5883 7.73112C13.5963 7.47047 13.5307 7.21269 13.4441 7.04123C13.1194 6.38676 12.3822 6.13407 11.7872 6.48936L11.7916 6.49461Z" fill="white"/></g></svg></span>','<span class="__crossx-wc-part __crossx-wc-part--rotated" style="left:76.25%;top:55.32%;width:16.5%;height:17.24%;--x0:-103.5548px;--y0:-33.6647px;--r0:-46.0deg;--x1:22.782px;--y1:7.4062px;--r1:11.0deg"><svg style="transform:matrix(0.77594,0.63081,-0.63611,0.77160,0,0)" preserveAspectRatio="none" width="30.7832" height="34.053" viewBox="0 0 30.7832 34.053" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M23.0894 4.85667C29.1483 7.06598 31.8871 14.815 29.2084 22.1775C26.5297 29.54 19.4419 33.7155 13.383 31.5164L8.9636 29.5717L19.6476 3.49238L23.0894 4.85667Z" fill="#F21C69"/><path d="M26.5372 20.5162C28.8822 13.04 25.7931 5.41697 19.6376 3.48967C13.4821 1.56238 6.59101 6.06065 4.24601 13.5368C1.901 21.013 4.99004 28.636 11.1456 30.5633C17.3011 32.4906 24.1922 27.9924 26.5372 20.5162Z" fill="url(#__cx-wc-7d32a-paint0_linear_0_47)"/><path d="M17.7415 5.16219C18.3321 5.27416 18.8921 5.4574 19.4317 5.70174C19.1976 5.63048 18.943 5.5694 18.6986 5.51851C13.5159 4.50062 8.26144 9.00146 6.97804 15.5283C6.23449 19.3059 6.98775 23.1649 8.98332 25.8732C9.92002 27.1459 11.0706 28.103 12.3637 28.6935C10.6735 28.1845 9.1869 27.0951 8.03639 25.5169C6.04081 22.7984 5.29774 18.9292 6.03111 15.1618C7.31451 8.62478 12.5791 4.13412 17.7517 5.15201L17.7415 5.16219Z" fill="#F21C69"/><path d="M16.2181 8.98864L11.5789 11.7932C10.7607 12.2852 10.447 13.4372 10.8805 14.3501C11.314 15.263 12.3404 15.6061 13.1586 15.1141L17.0826 12.7409L15.1828 14.8857L14.9169 23.5191C14.8848 24.5594 15.6167 25.4318 16.5454 25.4603C17.474 25.4887 18.2582 24.6627 18.2903 23.6225L18.6883 10.7006C18.6994 10.3396 18.6092 9.98272 18.4901 9.74532C18.0438 8.83915 17.0302 8.48935 16.212 8.98137L16.2181 8.98864Z" fill="white"/></g><defs><linearGradient id="__cx-wc-7d32a-paint0_linear_0_47" x1="10.0062" y1="30.4051" x2="22.1393" y2="4.29565" gradientUnits="userSpaceOnUse"><stop stop-color="#FF85B2"/><stop offset="0.3" stop-color="#FF75A1"/><stop offset="0.69" stop-color="#FF6892"/><stop offset="1" stop-color="#FF648D"/></linearGradient></defs></svg></span>','<span class="__crossx-wc-part" style="left:9.15%;top:27.18%;width:10.41%;height:10.87%;--x0:104.3547px;--y0:44.0181px;--r0:46.0deg;--x1:-22.958px;--y1:-9.684px;--r1:-11.0deg"><svg preserveAspectRatio="none" width="28.7144" height="28.8038" viewBox="0 0 28.7144 28.8038" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M5.69433 2.84346C-0.253684 5.91837 -1.78668 13.9558 2.26042 20.7957C6.31774 27.6356 14.4222 30.6801 20.3702 27.6051L24.6421 25.0275L9.05669 0.986328L5.69433 2.84346Z" fill="url(#__cx-wc-fc6d3-paint0_linear_0_27)"/><path d="M26.8181 8.56904C23.0981 1.56676 15.1469 -1.82275 9.05586 0.988314C2.96477 3.79937 1.04342 11.7657 4.76348 18.768C8.48354 25.7703 16.4347 29.1598 22.5258 26.3487C28.6168 23.5377 30.5382 15.5713 26.8181 8.56904Z" fill="url(#__cx-wc-fc6d3-paint1_linear_0_27)"/><path d="M21.5361 24.4592C20.974 24.7231 20.3812 24.9159 19.7783 25.0377C20.0235 24.9565 20.2688 24.8448 20.5141 24.7434C25.5014 22.4397 26.9833 15.7216 23.8254 9.76456C21.996 6.32431 18.8687 3.71621 15.445 2.76228C13.8405 2.31575 12.2564 2.24472 10.7949 2.55932C12.5425 1.95042 14.4843 1.91997 16.467 2.47813C19.8907 3.43206 23.018 6.05031 24.8576 9.48041C28.0155 15.4273 26.5336 22.1556 21.5463 24.4592H21.5361Z" fill="#F21C69"/><path d="M14.2883 5.68047L9.9279 9.22654C9.15843 9.84935 9.01876 11.0458 9.61565 11.8823C10.2125 12.7188 11.3327 12.8921 12.1022 12.2693L15.7902 9.26895L14.1652 11.7114L15.2815 20.3365C15.416 21.3758 16.316 22.1234 17.284 21.9998C18.2519 21.8763 18.9323 20.9271 18.7978 19.8878L17.127 6.97832C17.0803 6.61775 16.9292 6.27771 16.7673 6.06121C16.1582 5.23343 15.0503 5.05142 14.2808 5.67424L14.2883 5.68047Z" fill="white"/></g><defs><linearGradient id="__cx-wc-fc6d3-paint0_linear_0_27" x1="-0.164129" y1="13.6703" x2="25.534" y2="16.3173" gradientUnits="userSpaceOnUse"><stop stop-color="#FF4A8D"/><stop offset="0.1" stop-color="#FB4489"/><stop offset="0.23" stop-color="#F1357F"/><stop offset="0.36" stop-color="#E11D6F"/><stop offset="0.4" stop-color="#DB1469"/><stop offset="0.74" stop-color="#DB1569"/><stop offset="0.86" stop-color="#DB1C69"/><stop offset="0.95" stop-color="#DB2869"/><stop offset="1" stop-color="#DB3569"/></linearGradient><linearGradient id="__cx-wc-fc6d3-paint1_linear_0_27" x1="2.69461" y1="12.3407" x2="28.8706" y2="15.037" gradientUnits="userSpaceOnUse"><stop stop-color="#FF85B2"/><stop offset="0.3" stop-color="#FF75A1"/><stop offset="0.69" stop-color="#FF6892"/><stop offset="1" stop-color="#FF648D"/></linearGradient></defs></svg></span>','<span class="__crossx-wc-part" style="left:75.64%;top:27.76%;width:8.3%;height:10.48%;--x0:-76.2471px;--y0:42.9853px;--r0:-46.0deg;--x1:16.7744px;--y1:-9.4568px;--r1:11.0deg"><svg preserveAspectRatio="none" width="22.8957" height="27.775" viewBox="0 0 22.8957 27.775" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M14.2637 27.5528C12.1073 28.7908 7.40613 24.7315 3.76783 18.4904C0.119304 12.2391 -1.08665 6.18058 1.06976 4.93235L5.70963 2.24306L18.9036 24.8635L14.2637 27.5528Z" fill="#6D45D2"/><path d="M19.026 24.74C21.1632 23.4729 19.8745 17.4211 16.1477 11.223C12.4208 5.02483 7.66706 1.02742 5.52988 2.2945C3.39269 3.56159 4.68137 9.61335 8.40822 15.8115C12.1351 22.0096 16.8888 26.007 19.026 24.74Z" fill="#A872FF"/><path d="M15.1838 11.7804C18.4951 17.2706 19.8748 22.5173 18.26 23.461C18.0965 23.5625 17.9126 23.6031 17.7184 23.6031C17.7695 23.593 17.8206 23.5727 17.8615 23.5422C19.466 22.5984 18.0863 17.362 14.7852 11.8616C11.8112 6.90928 8.28536 3.42843 6.43555 3.48932C8.12184 2.78909 11.9748 6.43231 15.1838 11.7804Z" fill="#6D45D2"/><path d="M8.50038 6.8516L7.92883 10.3329C7.82678 10.9448 8.24482 11.9586 8.85575 12.5835C9.46668 13.2085 10.0504 13.2176 10.1525 12.6057L10.6355 9.6603L10.8741 11.8917L14.8619 18.9437C15.3424 19.7935 16.0565 20.3077 16.4508 20.0878C16.8451 19.868 16.7747 18.9949 16.2942 18.1452L10.3257 7.59022C10.159 7.29542 9.95265 7.03032 9.79113 6.86948C9.17811 6.2533 8.59648 6.23544 8.49443 6.84732L8.50038 6.8516Z" fill="white"/></g></svg></span>','<span class="__crossx-wc-part __crossx-wc-part--rotated" style="left:19.56%;top:63.74%;width:9%;height:10.13%;--x0:81.0429px;--y0:-56.7374px;--r0:46.0deg;--x1:-17.8294px;--y1:12.4822px;--r1:-11.0deg"><svg style="transform:matrix(0.92726,-0.37441,0.37920,0.92531,0,0)" preserveAspectRatio="none" width="17.8794" height="21.7754" viewBox="0 0 17.8794 21.7754" fill="none" xmlns="http://www.w3.org/2000/svg"><g><path d="M11.1385 21.5985C9.45751 22.5682 5.78879 19.3821 2.94775 14.4856C0.0987301 9.58109 -0.845253 4.82918 0.835783 3.8515L4.45281 1.74512L14.7556 19.4921L11.1385 21.5985Z" fill="#6D45D2"/><path d="M14.8635 19.3867C16.5291 18.3968 15.5168 13.6557 12.6025 8.79715C9.68823 3.9386 5.97547 0.802455 4.30984 1.79238C2.64422 2.7823 3.65647 7.52343 6.57077 12.382C9.48508 17.2405 13.1979 20.3767 14.8635 19.3867Z" fill="#A872FF"/><path d="M11.8531 9.22923C14.4381 13.5359 15.5168 17.6505 14.2582 18.3897C14.1308 18.4692 13.9874 18.5009 13.836 18.5008C13.8758 18.4929 13.9157 18.477 13.9475 18.4531C15.1981 17.714 14.1194 13.6073 11.5424 9.29267C9.22073 5.40791 6.46956 2.67665 5.02725 2.72338C6.34171 2.17526 9.34796 5.03401 11.8531 9.22923Z" fill="#6D45D2"/><path d="M6.63149 5.36631L6.18974 8.09188C6.11085 8.57093 6.43802 9.36528 6.91517 9.85536C7.39233 10.3454 7.84757 10.3532 7.92645 9.87417L8.29976 7.5682L8.48844 9.31584L11.6064 14.8428C11.9821 15.5087 12.5396 15.9122 12.8468 15.7405C13.1541 15.5688 13.0982 14.885 12.7225 14.2191L8.05583 5.94677C7.92549 5.71573 7.76427 5.5079 7.63813 5.38176C7.15934 4.89855 6.70573 4.8839 6.62685 5.36295L6.63149 5.36631Z" fill="white"/></g></svg></span>','<span class="__crossx-wc-wallet"><svg style="transform:matrix(0.97379,0.22745,-0.22745,0.97379,0,0)" width="88.42" height="88.42" viewBox="0 0 88.42 88.42" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><clipPath id="__cx-wc-wallet-clip"><path d="M44.2101 1.58818e-05C9.30971 1.58818e-05 0 9.30973 0 44.2101C0 79.1105 9.30971 88.4202 44.2101 88.4202C79.1105 88.4202 88.4202 79.1105 88.4202 44.2101C88.4202 9.30973 79.1105 1.58818e-05 44.2101 1.58818e-05Z"/></clipPath><clipPath id="__cx-wc-wallet-clip2"><path transform="translate(0.1 0.01)" d="M44.2101 1.58818e-05C9.30971 1.58818e-05 0 9.30973 0 44.2101C0 79.1105 9.30971 88.4202 44.2101 88.4202C79.1105 88.4202 88.4202 79.1105 88.4202 44.2101C88.4202 9.30973 79.1105 1.58818e-05 44.2101 1.58818e-05Z"/></clipPath></defs><g clip-path="url(#__cx-wc-wallet-clip)"><svg x="0.000" y="0.044" width="88.393" height="88.376" viewBox="0 0 88.3978 88.3761" preserveAspectRatio="none" overflow="visible"><g><path d="M88.3761 0L0 0L0 88.3761H88.3761V0Z" fill="url(#__cx-wc-ab720-paint0_linear_0_228)"/><g><path d="M30.885 88.3759H88.3978V16.8103L30.885 53.652L30.885 88.3759Z" fill="url(#__cx-wc-ab720-paint1_linear_0_228)"/><path d="M30.8867 88.3754H0.00143051L0.00143051 21.0013L30.8867 53.6515L30.8867 88.3754Z" fill="url(#__cx-wc-ab720-paint2_linear_0_228)"/></g></g><defs><linearGradient id="__cx-wc-ab720-paint0_linear_0_228" x1="-10.2363" y1="-10.6554" x2="94.2222" y2="94.5531" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="__cx-wc-ab720-paint1_linear_0_228" x1="22.0606" y1="20.2959" x2="65.1015" y2="57.2921" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="__cx-wc-ab720-paint2_linear_0_228" x1="55.1317" y1="3.02165" x2="14.4513" y2="55.9899" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient></defs></svg></g><g clip-path="url(#__cx-wc-wallet-clip2)"><rect y="0.44" width="88.42" height="88.42" fill="#fff"/><svg x="-2.750" y="0.413" width="93.929" height="93.140" viewBox="0 0 93.9211 93.1421" preserveAspectRatio="none" overflow="visible"><g><path d="M91.1837 0H2.76347L2.76347 88.4202H91.1837V0Z" fill="#CE3E35"/><path d="M13.5066 17.7839C13.5066 13.7731 16.758 10.5216 20.7689 10.5216H73.1521C77.163 10.5216 80.4144 13.7731 80.4144 17.7839V47.0786H13.5066L13.5066 17.7839Z" fill="white"/><g filter="url(#__cx-wc-050c7-filter0_d_0_83)"><path d="M91.158 91.0698H2.76313L2.76313 24.5964C2.76313 21.5443 5.23732 19.0701 8.28939 19.0701H32.9437C35.5525 19.0701 37.6858 21.0278 39.2584 23.1092C41.0469 25.4762 43.8319 26.9978 46.9604 26.9978C50.0889 26.9978 52.874 25.4762 54.6625 23.1092C56.2352 21.0278 58.3685 19.0701 60.9772 19.0701H85.6317C88.6838 19.0701 91.158 21.5443 91.158 24.5964V91.0698Z" fill="url(#__cx-wc-050c7-paint0_linear_0_83)"/></g><g><path d="M33.643 91.0285H91.1559V27.7523L33.643 64.594V91.0285Z" fill="url(#__cx-wc-050c7-paint1_linear_0_83)"/><path d="M33.6463 91.0735H2.76103L2.76103 32.0876L33.6463 64.7378V91.0735Z" fill="url(#__cx-wc-050c7-paint2_linear_0_83)"/></g></g><defs><filter id="__cx-wc-050c7-filter0_d_0_83" x="8.9407e-08" y="15.6162" width="93.9211" height="77.5259" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dy="-0.690783"/><feGaussianBlur stdDeviation="1.38157"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.892803 0 0 0 0 0.220099 0 0 0 0 0.293135 0 0 0 0.5 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_0_83"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_0_83" result="shape"/></filter><linearGradient id="__cx-wc-050c7-paint0_linear_0_83" x1="-7.47531" y1="10.2228" x2="77.666" y2="113.52" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="__cx-wc-050c7-paint1_linear_0_83" x1="24.8187" y1="31.2379" x2="67.8595" y2="68.2341" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="__cx-wc-050c7-paint2_linear_0_83" x1="57.8913" y1="14.108" x2="17.211" y2="67.0762" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient></defs></svg><svg x="26.299" y="32.289" width="29.201" height="48.231" viewBox="0 0 29.1992 48.2295" preserveAspectRatio="none" overflow="visible"><g filter="url(#__cx-wc-2c959-filter0_d_0_4)"><path d="M17.5095 3.62052L5.20252 10.7339C3.03172 11.9822 2.27963 14.7865 3.52741 16.9582C4.7752 19.1298 7.57844 19.8822 9.74925 18.6339L20.1589 12.6149L15.2019 17.9328L15.2019 38.7943C15.2019 41.3079 17.2531 43.3598 19.7657 43.3598C22.2784 43.3598 24.3295 41.3079 24.3295 38.7943V7.57051C24.3295 6.69844 24.0561 5.84346 23.7142 5.27917C22.4322 3.12463 19.6632 2.35515 17.4924 3.60342L17.5095 3.62052Z" fill="white"/><g></g></g><defs><filter id="__cx-wc-2c959-filter0_d_0_4" x="-4.91855e-08" y="0.0794639" width="29.1992" height="48.15" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="0.972558" dy="0.972558"/><feGaussianBlur stdDeviation="1.94855"/><feColorMatrix type="matrix" values="0 0 0 0 0.831373 0 0 0 0 0.113725 0 0 0 0 0.356863 0 0 0 0.3 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_0_4"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_0_4" result="shape"/></filter></defs></svg></g></svg></span>'].join(""),vc=`
8
- .__crossx-wallet-created-illust {
9
- display: block;
10
- position: relative;
11
- width: 276px;
12
- height: 265px;
13
- flex: none;
14
- }
15
- .__crossx-wc-part,
16
- .__crossx-wc-wallet {
17
- position: absolute;
18
- display: block;
19
- transform-origin: 50% 50%;
20
- }
21
- .__crossx-wc-part > svg,
22
- .__crossx-wc-wallet > svg {
23
- display: block;
24
- flex: none;
25
- }
26
- .__crossx-wc-part--rotated,
27
- .__crossx-wc-wallet {
28
- display: flex;
29
- align-items: center;
30
- justify-content: center;
31
- }
32
- .__crossx-wc-part {
33
- animation: __crossx-wc-burst 2s linear both;
34
- }
35
- /* 별·파티클(흰 단색 조각)만 테마 색을 따른다 — 코인·지갑의 흰 '1' 은 그대로 흰색 */
36
- .__crossx-wc-sparkle path {
37
- fill: var(--cx-wc-sparkle, #FFFFFF);
38
- }
39
- .__crossx-wc-wallet {
40
- left: 79.65px;
41
- top: 86.91px;
42
- width: 106.214px;
43
- height: 106.214px;
44
- animation:
45
- __crossx-wc-wallet-rise 2s linear both,
46
- __crossx-wc-wallet-tilt 2s linear both,
47
- __crossx-wc-wallet-fade 2s linear both;
48
- }
49
- /* 코인·반짝이: 지갑 중심에서 튀어나와(1.28배) 스프링으로 제자리 */
50
- @keyframes __crossx-wc-burst {
51
- 0%, 13.5% {
52
- translate: var(--x0) var(--y0);
53
- rotate: var(--r0);
54
- scale: 0.045;
55
- animation-timing-function: cubic-bezier(0.08, 0.82, 0.18, 1);
56
- }
57
- 23.5% {
58
- translate: var(--x1) var(--y1);
59
- rotate: var(--r1);
60
- scale: 1.28;
61
- animation-timing-function: ${yr};
62
- }
63
- 37.5%, 100% {
64
- translate: 0px 0px;
65
- rotate: 0deg;
66
- scale: 1;
67
- }
68
- }
69
- /* 지갑: 아래에서 솟아오르며 살짝 눌렸다 복원 */
70
- @keyframes __crossx-wc-wallet-rise {
71
- 0%, 0.053% {
72
- translate: 0px 104px;
73
- scale: 0.9 0.9;
74
- animation-timing-function: cubic-bezier(0.14, 0.74, 0.24, 1);
75
- }
76
- 27.247% {
77
- translate: 0px -5px;
78
- scale: 1.035 0.975;
79
- animation-timing-function: ${yr};
80
- }
81
- 37.445%, 100% {
82
- translate: 0px 0px;
83
- scale: 1 1;
84
- }
85
- }
86
- /* 지갑: 좌우로 흔들리다 정지 */
87
- @keyframes __crossx-wc-wallet-tilt {
88
- 0%, 0.053% { rotate: -11.0deg; animation-timing-function: ease-in-out; }
89
- 9.118% { rotate: 8.0deg; animation-timing-function: ease-in-out; }
90
- 17.616% { rotate: -5.0deg; animation-timing-function: ease-in-out; }
91
- 26.114% { rotate: 2.5deg; animation-timing-function: ${yr}; }
92
- 36.312%, 100% { rotate: 0deg; }
93
- }
94
- @keyframes __crossx-wc-wallet-fade {
95
- 0% { opacity: 0; animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1); }
96
- 8%, 100% { opacity: 1; }
97
- }
98
- @media (prefers-reduced-motion: reduce) {
99
- .__crossx-wc-part,
100
- .__crossx-wc-wallet {
101
- animation: none;
102
- }
103
- }
104
- `,vn="__crossx-confirm-style",Y="__crossx-confirm-overlay",Ec={light:{bg:"#FFFFFF",border:"rgba(0,0,0,0.07)",borderMedium:"rgba(0,0,0,0.18)",titleColor:"#000000",contentHigh:"rgba(0,0,0,0.85)",subtitleColor:"rgba(0,0,0,0.65)",labelColor:"rgba(0,0,0,0.65)",valueColor:"#000000",pillBg:"#F5F7FA",pillFromColor:"rgba(0,0,0,0.65)",pillAmtColor:"#000000",divider:"rgba(0,0,0,0.07)",closeColor:"rgba(0,0,0,0.40)",closeHoverBg:"#F5F7FA",copyColor:"rgba(0,0,0,0.65)",inputBg:"#F5F7FA",inputBorder:"rgba(0,0,0,0.07)",hintColor:"rgba(0,0,0,0.45)",surfaceSubtle:"#F5F7FA",surfaceHigh:"#EDF1F2",primary:"#7E54F4",primaryGlow:"rgba(126,84,244,0.20)",primaryGradient:"#7E54F4",secondary:"#D20609",errorColor:"#D20609",noticeBg:"#FFF6F6",noticeBorder:"#DA0B2E",noticeTitleColor:"#D20609",onPrimary:"#FFFFFF",sparkleColor:"#FFAA1F",warningColor:"#E56F00"},dark:{bg:"#1E232E",border:"rgba(255,255,255,0.07)",borderMedium:"rgba(255,255,255,0.18)",titleColor:"#FFFFFF",contentHigh:"rgba(255,255,255,0.85)",subtitleColor:"rgba(255,255,255,0.65)",labelColor:"rgba(255,255,255,0.65)",valueColor:"#FFFFFF",pillBg:"#252B39",pillFromColor:"rgba(255,255,255,0.65)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.07)",closeColor:"rgba(255,255,255,0.40)",closeHoverBg:"#252B39",copyColor:"rgba(255,255,255,0.65)",inputBg:"#252B39",inputBorder:"rgba(255,255,255,0.07)",hintColor:"rgba(255,255,255,0.45)",surfaceSubtle:"#252B39",surfaceHigh:"#363B4C",primary:"#A392FF",primaryGlow:"rgba(163,146,255,0.20)",primaryGradient:"#A392FF",secondary:"#FF0F47",errorColor:"#EA1546",noticeBg:"#39151E",noticeBorder:"#CD0C40",noticeTitleColor:"#EA1546",onPrimary:"#000000",sparkleColor:"#FFFFFF",warningColor:"#FF9F21"}};function Ic(s,e){const r=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(s.trim());if(!r)return;const t=r[1].length===3?r[1].split("").map(i=>i+i).join(""):r[1],n=parseInt(t,16);return`rgba(${n>>16&255},${n>>8&255},${n&255},${e})`}function En(s,e){const r=Ec[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary,primaryGradient:t.primary,primaryGlow:Ic(t.primary,.2)??r.primaryGlow},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault,borderMedium:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary,contentHigh:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle,surfaceHigh:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const Ac=`
105
- @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400&family=Sora:wght@400;600&display=swap');
106
-
107
- #${Y} {
108
- position: fixed;
109
- inset: 0;
110
- z-index: 2147483647;
111
- display: flex;
112
- align-items: center;
113
- justify-content: center;
114
- background: rgba(0,0,0,0.55);
115
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
116
- /* Figma 렌더와 같은 굵기로 보이도록 서브픽셀 대신 그레이스케일 안티앨리어싱(macOS) — 하위 요소에 상속 */
117
- -webkit-font-smoothing: antialiased;
118
- -moz-osx-font-smoothing: grayscale;
119
- text-rendering: optimizeLegibility;
120
- animation: __crossx-fade-in 0.15s ease;
121
- pointer-events: auto;
122
- }
123
- @keyframes __crossx-fade-in {
124
- from { opacity: 0; }
125
- to { opacity: 1; }
126
- }
127
-
128
- /* ── 버튼 호버·프레스 공통 ─────────────────────────────────────────
129
- 호스트 페이지의 전역 \`button:hover\` (떠오름 + 글로우 그림자)가 SDK 버튼에 새지 않게 막고,
130
- 모든 버튼의 피드백은 배경·보더가 밝아지는 방식으로 통일한다. (넘패드 하단선 그림자는 !important 라 유지) */
131
- #${Y} button:is(:hover, :focus, :active) {
132
- box-shadow: none;
133
- transform: none;
134
- }
135
- /* 채움형 CTA — 호버 시 한 단계 밝게, 누르면 살짝 어둡게.
136
- color-mix 를 모르는 브라우저(Chrome·WebView 111 미만, Safari 16.2 미만)에서는 값이 무효가 돼
137
- 배경이 투명해지므로 @supports 로 감싼다. 미지원 환경은 기본 배경 그대로 두고 눌림만 남긴다. */
138
- @supports (color: color-mix(in srgb, red, blue)) {
139
- #${Y} :is(.__crossx-approve-btn, .__crossx-confirm-btn, .__crossx-wallet-created-btn, .__crossx-pw-btn, .__crossx-pin6-next):not(:disabled):not(.--disabled):not([aria-disabled="true"]):hover {
140
- background: color-mix(in srgb, var(--cx-primary-gradient) 86%, #FFFFFF) !important;
141
- }
142
- #${Y} :is(.__crossx-approve-btn, .__crossx-confirm-btn, .__crossx-wallet-created-btn, .__crossx-pw-btn, .__crossx-pin6-next):not(:disabled):not(.--disabled):not([aria-disabled="true"]):active {
143
- background: color-mix(in srgb, var(--cx-primary-gradient) 90%, #000000) !important;
144
- }
145
- }
146
- /* 보조(취소) — 호버·프레스 시 한 단계 밝은 표면 */
147
- #${Y} .__crossx-cancel-btn:not(:disabled):is(:hover, :active) {
148
- background: var(--cx-surface-high) !important;
149
- }
150
- /* 표면형 — 호버 시 한 단계 밝은 표면 */
151
- #${Y} :is(.__crossx-recover-btn, .__crossx-connect-other-block):not(:disabled):hover {
152
- background: var(--cx-surface-high) !important;
153
- }
154
- /* 지갑 추가(점선) — 표면 + 점선 보더가 밝아진다 */
155
- #${Y} .__crossx-wallet-add:not(:disabled):hover {
156
- background: var(--cx-pill-bg);
157
- border-color: var(--cx-subtitle);
158
- }
159
- /* 기존 눌림 스케일은 유지 (공통 reset 보다 우선) */
160
- #${Y} .__crossx-close:active {
161
- transform: scale(0.92);
162
- }
163
- #${Y} .__crossx-wallet-item:active {
164
- transform: scale(0.985);
165
- }
166
- #${Y} .__crossx-wallet-add:not(:disabled):active {
167
- transform: scale(0.99);
168
- }
169
-
170
- /* 비활성 버튼은 호버·포커스·프레스 효과 없음 — SDK 자체 효과뿐 아니라 호스트 페이지의
171
- 전역 \`button:hover\` (떠오름·그림자 등)도 막는다. SDK 는 비활성을 \`.--disabled\` 클래스로도
172
- 표시하므로 \`:disabled\` 만으로는 호스트 규칙을 피할 수 없다. 커서는 모두 not-allowed. */
173
- #${Y} button:is(:disabled, .--disabled, [aria-disabled="true"]) {
174
- cursor: not-allowed !important;
175
- }
176
- #${Y} button:is(:disabled, .--disabled, [aria-disabled="true"]):is(:hover, :focus, :active) {
177
- transform: none !important;
178
- filter: none !important;
179
- }
180
- /* 넘패드 키는 하단선을 box-shadow 로 그리므로 그림자 제거에서 뺀다 */
181
- #${Y} button:is(:disabled, .--disabled, [aria-disabled="true"]):not(.__crossx-pin6-numpad-key):is(:hover, :focus, :active) {
182
- box-shadow: none !important;
183
- }
184
-
185
- .__crossx-card {
186
- background: var(--cx-bg);
187
- border: 1px solid var(--cx-border-medium);
188
- border-radius: 24px;
189
- width: 383px;
190
- max-width: calc(100vw - 32px);
191
- overflow: hidden;
192
- position: relative;
193
- animation: __crossx-slide-up 0.18s ease;
194
- box-sizing: border-box;
195
- box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
196
- }
197
- @keyframes __crossx-slide-up {
198
- from { transform: translateY(20px); opacity: 0; }
199
- to { transform: translateY(0); opacity: 1; }
200
- }
201
-
202
- /* ── Header ─────────────────────────────────────────────────────── */
203
- .__crossx-header {
204
- padding: 24px;
205
- position: relative;
206
- }
207
- .__crossx-title {
208
- font-size: 20px;
209
- font-weight: 600;
210
- line-height: 1.25;
211
- color: var(--cx-title);
212
- margin: 0 0 4px 0;
213
- padding-right: 36px;
214
- letter-spacing: 0;
215
- }
216
- .__crossx-subtitle {
217
- font-size: 14px;
218
- font-weight: 400;
219
- line-height: 1.5;
220
- color: var(--cx-subtitle);
221
- margin: 0;
222
- letter-spacing: -0.01em;
223
- }
224
- .__crossx-close {
225
- position: absolute;
226
- top: 24px;
227
- right: 24px;
228
- width: 24px;
229
- height: 24px;
230
- border: none;
231
- background: none;
232
- cursor: pointer;
233
- color: var(--cx-close);
234
- border-radius: 6px;
235
- display: flex;
236
- align-items: center;
237
- justify-content: center;
238
- padding: 0;
239
- appearance: none;
240
- -webkit-appearance: none;
241
- box-shadow: none;
242
- outline: none;
243
- /* 아이콘 색은 content/low(--cx-close) 단일 알파값만 사용 — opacity 중첩 금지 */
244
- opacity: 1;
245
- transition: background-color 0.15s ease, color 0.15s ease, transform 0.1s ease;
246
- }
247
- .__crossx-close:hover {
248
- background: var(--cx-close-hover);
249
- color: var(--cx-subtitle);
250
- }
251
- .__crossx-close:active {
252
- background: var(--cx-close-hover);
253
- color: var(--cx-title);
254
- transform: scale(0.92);
255
- }
256
- .__crossx-close:focus-visible {
257
- outline: 2px solid var(--cx-primary);
258
- outline-offset: 2px;
259
- }
260
- .__crossx-close svg { display: block; }
261
-
262
- /* ── Divider ─────────────────────────────────────────────────────── */
263
- .__crossx-divider {
264
- border: none;
265
- border-top: 1px solid var(--cx-divider);
266
- margin: 0;
267
- }
268
-
269
- /* ── Body ────────────────────────────────────────────────────────── */
270
- .__crossx-body {
271
- padding: 20px 24px 24px;
272
- display: flex;
273
- flex-direction: column;
274
- gap: 16px;
275
- }
276
-
277
- /* Info rows */
278
- .__crossx-rows {
279
- display: flex;
280
- flex-direction: column;
281
- gap: 12px; /* Figma 행 간격 12 */
282
- }
283
- .__crossx-row {
284
- display: flex;
285
- align-items: center;
286
- min-height: 21px;
287
- }
288
- .__crossx-row-label {
289
- font-size: 14px;
290
- font-weight: 500;
291
- line-height: 1.5;
292
- letter-spacing: -0.01em;
293
- color: var(--cx-close); /* Figma content/low */
294
- width: 100px;
295
- flex-shrink: 0;
296
- }
297
- .__crossx-row-value {
298
- font-size: 14px;
299
- font-weight: 500;
300
- line-height: 1.5;
301
- letter-spacing: -0.01em;
302
- color: var(--cx-subtitle); /* Figma content/medium */
303
- flex: 1;
304
- text-align: right;
305
- display: flex;
306
- align-items: center;
307
- justify-content: flex-end;
308
- gap: 6px;
309
- min-width: 0;
310
- overflow: hidden;
311
- }
312
- .__crossx-addr-text {
313
- white-space: nowrap;
314
- overflow: hidden;
315
- text-overflow: ellipsis;
316
- }
317
- .__crossx-row-link {
318
- color: inherit;
319
- text-decoration: none;
320
- }
321
- .__crossx-row-link:hover,
322
- .__crossx-row-link:focus {
323
- text-decoration: underline;
324
- }
325
- .__crossx-copy-btn {
326
- background: none;
327
- border: none;
328
- cursor: pointer;
329
- color: var(--cx-copy);
330
- padding: 0;
331
- display: flex;
332
- align-items: center;
333
- flex-shrink: 0;
334
- opacity: 0.7;
335
- }
336
- .__crossx-copy-btn:hover,
337
- .__crossx-copy-btn:focus,
338
- .__crossx-copy-btn:active {
339
- opacity: 0.7 !important;
340
- box-shadow: none !important;
341
- outline: none !important;
342
- filter: none !important;
343
- transform: none !important;
344
- background: none !important;
345
- }
346
-
347
- /* Amount pill */
348
- .__crossx-pill {
349
- background: var(--cx-pill-bg);
350
- border-radius: 12px;
351
- padding: 16px;
352
- display: flex;
353
- align-items: center;
354
- gap: 8px;
355
- }
356
- .__crossx-pill-from {
357
- font-size: 14px;
358
- font-weight: 600;
359
- line-height: 1.5;
360
- letter-spacing: -0.01em;
361
- color: var(--cx-close); /* Figma content/low */
362
- white-space: nowrap;
363
- overflow: hidden;
364
- text-overflow: ellipsis;
365
- flex-shrink: 1;
366
- min-width: 0;
367
- }
368
- .__crossx-pill-amount {
369
- font-size: 18px;
370
- font-weight: 600;
371
- line-height: 1.5;
372
- letter-spacing: -0.01em;
373
- color: var(--cx-content-high); /* Figma content/high */
374
- text-align: right;
375
- white-space: nowrap;
376
- flex-shrink: 0;
377
- margin-left: auto;
378
- }
379
-
380
- /* Message box */
381
- .__crossx-msg-box {
382
- background: var(--cx-pill-bg);
383
- border-radius: 12px;
384
- padding: 16px;
385
- max-height: 160px;
386
- overflow-y: auto;
387
- word-break: break-all;
388
- font-size: 13px;
389
- font-weight: 400;
390
- line-height: 1.5;
391
- color: var(--cx-value);
392
- white-space: pre-wrap;
393
- }
394
-
395
-
396
- /* ── Password Modals ───────────────────────────────────────────── */
397
- .__crossx-card--password {
398
- width: 560px;
399
- display: flex;
400
- flex-direction: column;
401
- max-height: 90vh;
402
- }
403
- .__crossx-pw-body {
404
- padding: 20px 64px 24px;
405
- display: flex;
406
- flex-direction: column;
407
- gap: 24px;
408
- overflow: hidden;
409
- flex: 1;
410
- min-height: 0;
411
- }
412
- .__crossx-pw-fields {
413
- display: flex;
414
- flex-direction: column;
415
- gap: 24px;
416
- }
417
- .__crossx-pw-fields--setup {
418
- flex: 1;
419
- min-height: 0;
420
- overflow-y: auto;
421
- -webkit-overflow-scrolling: touch;
422
- }
423
- .__crossx-pw-fg--confirm {
424
- margin-top: 8px;
425
- }
426
- .__crossx-pw-field-group {
427
- display: flex;
428
- flex-direction: column;
429
- gap: 8px;
430
- }
431
- .__crossx-pw-label {
432
- font-size: 14px;
433
- font-weight: 400;
434
- line-height: 1.4;
435
- color: var(--cx-value);
436
- }
437
- .__crossx-pw-input-wrap {
438
- position: relative;
439
- display: flex;
440
- align-items: center;
441
- background: var(--cx-input-bg);
442
- border: 1px solid var(--cx-input-border);
443
- border-radius: 12px;
444
- height: 56px;
445
- padding: 0 16px;
446
- transition: border-color 0.15s;
447
- }
448
- .__crossx-pw-input-wrap:focus-within {
449
- border-color: var(--cx-primary);
450
- }
451
- .__crossx-pw-input-wrap.--error {
452
- background: rgba(231,0,119,0.08);
453
- border-color: var(--cx-error);
454
- }
455
- .__crossx-pw-input {
456
- flex: 1;
457
- border: none;
458
- background: transparent;
459
- font-size: 16px;
460
- font-family: inherit;
461
- color: var(--cx-value);
462
- outline: none;
463
- padding: 0;
464
- min-width: 0;
465
- }
466
- .__crossx-pw-input::placeholder {
467
- color: var(--cx-hint);
468
- }
469
- .__crossx-pw-toggle {
470
- background: none;
471
- border: none;
472
- cursor: pointer;
473
- color: var(--cx-hint);
474
- padding: 4px;
475
- display: flex;
476
- align-items: center;
477
- flex-shrink: 0;
478
- opacity: 0.7;
479
- }
480
- .__crossx-pw-toggle:hover { opacity: 1; }
481
- .__crossx-pw-rules {
482
- display: flex;
483
- flex-direction: column;
484
- gap: 8px;
485
- }
486
- .__crossx-pw-rule {
487
- display: flex;
488
- align-items: center;
489
- gap: 8px;
490
- }
491
- .__crossx-pw-rule-dot {
492
- width: 16px;
493
- height: 16px;
494
- border-radius: 50%;
495
- background: var(--cx-input-border);
496
- display: flex;
497
- align-items: center;
498
- justify-content: center;
499
- flex-shrink: 0;
500
- transition: background 0.15s;
501
- }
502
- .__crossx-pw-rule-dot.--met {
503
- background: var(--cx-primary);
504
- }
505
- .__crossx-pw-rule-dot svg {
506
- width: 9px;
507
- height: 7px;
508
- }
509
- .__crossx-pw-rule-text {
510
- font-size: 14px;
511
- font-weight: 400;
512
- line-height: 1.4;
513
- color: var(--cx-value);
514
- }
515
- .__crossx-pw-error-text {
516
- font-size: 14px;
517
- font-weight: 400;
518
- line-height: 1.4;
519
- color: var(--cx-error);
520
- margin-top: 4px;
521
- }
522
- .__crossx-pw-confirm-group {
523
- display: flex;
524
- flex-direction: column;
525
- gap: 24px;
526
- }
527
- .__crossx-pw-confirm-group.--has-error {
528
- gap: 16px;
529
- }
530
- .__crossx-pw-lock {
531
- display: flex;
532
- align-items: center;
533
- flex-shrink: 0;
534
- color: var(--cx-hint);
535
- opacity: 0.6;
536
- pointer-events: none;
537
- }
538
- .__crossx-pw-btn {
539
- width: 100%;
540
- border: none;
541
- border-radius: 12px;
542
- font-family: inherit;
543
- cursor: pointer;
544
- transition: opacity 0.15s;
545
- /* disabled 기본값 = 브랜드 그라데이션 50% 투명도 */
546
- background: var(--cx-primary-gradient);
547
- color: var(--cx-on-primary);
548
- opacity: 0.5;
549
- letter-spacing: -0.01em;
550
- }
551
- .__crossx-pw-btn:not(:disabled):not(.--disabled) {
552
- opacity: 1;
553
- }
554
- .__crossx-pw-btn.--loading {
555
- opacity: 0.6;
556
- cursor: not-allowed;
557
- }
558
- .__crossx-pw-subtitle {
559
- font-size: 14px;
560
- font-weight: 400;
561
- line-height: 1.5;
562
- color: var(--cx-subtitle);
563
- margin: 0;
564
- letter-spacing: -0.01em;
565
- }
566
-
567
- /* ── Password Notice (Consent) Screen ─────────────────────────── */
568
- .__crossx-pw-notice-header {
569
- display: flex;
570
- flex-direction: column;
571
- gap: 6px;
572
- padding: 12px;
573
- border: 0.5px solid var(--cx-notice-border);
574
- border-radius: 12px;
575
- background: var(--cx-notice-bg);
576
- }
577
- .__crossx-pw-notice-title-row {
578
- display: flex;
579
- align-items: center;
580
- gap: 6px;
581
- }
582
- .__crossx-pw-notice-icon {
583
- width: 20px;
584
- height: 20px;
585
- flex-shrink: 0;
586
- color: var(--cx-notice-title);
587
- }
588
- .__crossx-pw-notice-icon svg {
589
- display: block;
590
- width: 100%;
591
- height: 100%;
592
- }
593
- .__crossx-pw-notice-title {
594
- font-size: 16px;
595
- font-weight: 600;
596
- line-height: 1.5;
597
- color: var(--cx-notice-title);
598
- margin: 0;
599
- white-space: nowrap;
600
- letter-spacing: -0.01em;
601
- }
602
- .__crossx-pw-notice-desc {
603
- font-size: 14px;
604
- font-weight: 400;
605
- line-height: 1.5;
606
- color: var(--cx-value);
607
- margin: 0;
608
- letter-spacing: -0.01em;
609
- }
610
- .__crossx-pw-notice-checks {
611
- display: flex;
612
- flex-direction: column;
613
- gap: 16px;
614
- }
615
- .__crossx-pw-notice-item {
616
- display: flex;
617
- align-items: flex-start;
618
- gap: 8px;
619
- padding: 0;
620
- border-radius: 0;
621
- background: transparent;
622
- cursor: pointer;
623
- user-select: none;
624
- transition: background 0.15s;
625
- }
626
- .__crossx-pw-notice-item:hover {
627
- background: transparent;
628
- }
629
- .__crossx-pw-notice-item.--highlight {
630
- animation: __crossx-notice-pulse 0.5s ease;
631
- }
632
- @keyframes __crossx-notice-pulse {
633
- 0% { background: var(--cx-input-bg); }
634
- 40% { background: rgba(1,157,146,0.18); }
635
- 100% { background: var(--cx-input-bg); }
636
- }
637
- .__crossx-pw-notice-check {
638
- width: 20px;
639
- height: 20px;
640
- border-radius: 50%;
641
- border: 1px solid var(--cx-border-medium);
642
- background: transparent;
643
- color: var(--cx-on-primary);
644
- display: flex;
645
- align-items: center;
646
- justify-content: center;
647
- flex-shrink: 0;
648
- transition: background 0.15s;
649
- }
650
- .__crossx-pw-notice-check.--checked {
651
- background: var(--cx-primary);
652
- border-color: var(--cx-primary);
653
- }
654
- .__crossx-pw-notice-check svg {
655
- width: 11px;
656
- height: 9px;
657
- }
658
- /* Figma: 체크 전에는 빈 원 — 체크 표시는 선택됐을 때만 보인다 */
659
- .__crossx-pw-notice-check:not(.--checked) svg {
660
- visibility: hidden;
661
- }
662
- .__crossx-pw-notice-item-text {
663
- font-size: 14px;
664
- font-weight: 400;
665
- line-height: 1.5;
666
- color: var(--cx-subtitle);
667
- flex: 1;
668
- letter-spacing: -0.01em;
669
- }
670
- /* Notice screen: disabled 버튼은 50% 투명도로 표시하되 탭하면 미체크 항목을 안내 */
671
- .__crossx-pw-body > .__crossx-pw-btn.--disabled {
672
- opacity: 0.5;
673
- cursor: pointer;
674
- }
675
- /* Home indicator bar (mobile only – shown via media query) */
676
- .__crossx-home-indicator {
677
- display: none;
678
- justify-content: center;
679
- align-items: flex-end;
680
- padding-bottom: 8px;
681
- height: 34px;
682
- flex-shrink: 0;
683
- width: 100%;
684
- }
685
- .__crossx-home-indicator::after {
686
- content: '';
687
- display: block;
688
- width: 134px;
689
- height: 5px;
690
- border-radius: 16px;
691
- background: var(--cx-value);
692
- opacity: 0.3;
693
- }
694
- .__crossx-pw-subtitle--tertiary {
695
- font-size: 14px;
696
- font-weight: 400;
697
- line-height: 1.3;
698
- color: var(--cx-hint);
699
- margin: 0;
700
- }
701
-
702
- /* ── Migration Found Modal ─────────────────────────────────────── */
703
- .__crossx-card--migration {
704
- width: 480px; /* 서명·전송 모달과 같은 폭(Figma 480) */
705
- }
706
- /* 세션 만료·업데이트 안내: Figma 4045:14458 — 본문 padding 24, gap 24 (인라인 스타일을 덮는다) */
707
- .__crossx-card--migration > .__crossx-body:has(> .__crossx-session-hero) {
708
- padding: 24px !important;
709
- gap: 24px !important;
710
- }
711
- /* Figma 커넥트 모달: 폭 540, 제목-부제목 간격 4 (래퍼 gap 4 만 쓰고 제목 margin 은 뺀다).
712
- 모바일의 \`.__crossx-card { width: 100% }\` 가 뒤에 선언돼 있어 시트 폭은 그대로다 */
713
- .__crossx-card--login {
714
- width: 540px;
715
- }
716
- .__crossx-card--login .__crossx-title {
717
- margin-bottom: 0;
718
- }
719
- .__crossx-login-sheet-handle {
720
- display: none;
721
- }
722
- .__crossx-subtitle--body {
723
- font-size: 16px;
724
- font-weight: 500;
725
- line-height: 1.5;
726
- color: var(--cx-subtitle);
727
- margin: 0;
728
- letter-spacing: -0.16px;
729
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
730
- }
731
- .__crossx-mig-info {
732
- display: flex;
733
- flex-direction: column;
734
- gap: 4px;
735
- }
736
- .__crossx-mig-info-title {
737
- font-size: 14px;
738
- font-weight: 600;
739
- line-height: 1.4;
740
- color: var(--cx-content-high); /* Figma content/high */
741
- margin: 0;
742
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
743
- }
744
- .__crossx-mig-info-desc {
745
- font-size: 14px;
746
- font-weight: 400;
747
- line-height: 1.4;
748
- color: var(--cx-subtitle);
749
- margin: 0;
750
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
751
- }
752
- .__crossx-recover-btn {
753
- display: flex;
754
- align-items: center;
755
- gap: 16px;
756
- width: 100%;
757
- padding: 16px;
758
- background: var(--cx-pill-bg);
759
- border: none;
760
- border-radius: 12px;
761
- cursor: pointer;
762
- appearance: none;
763
- -webkit-appearance: none;
764
- -webkit-tap-highlight-color: transparent;
765
- box-shadow: none;
766
- outline: none;
767
- }
768
- .__crossx-recover-btn:hover,
769
- .__crossx-recover-btn:focus,
770
- .__crossx-recover-btn:active {
771
- background: var(--cx-pill-bg) !important;
772
- border-color: var(--cx-pill-bg) !important;
773
- opacity: 1 !important;
774
- box-shadow: none !important;
775
- outline: none !important;
776
- filter: none !important;
777
- transform: none !important;
778
- }
779
- .__crossx-recover-icon {
780
- display: flex;
781
- align-items: center;
782
- justify-content: center;
783
- flex-shrink: 0;
784
- width: 40px;
785
- height: 40px;
786
- }
787
- .__crossx-recover-icon svg {
788
- width: 40px;
789
- height: 40px;
790
- display: block;
791
- }
792
- .__crossx-recover-label {
793
- font-size: 16px;
794
- font-weight: 600;
795
- line-height: 1.5;
796
- color: var(--cx-content-high);
797
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
798
- }
799
- .__crossx-skip-btn {
800
- font-size: 16px;
801
- font-weight: 400;
802
- line-height: 1.3;
803
- color: var(--cx-subtitle);
804
- text-decoration: underline;
805
- cursor: pointer;
806
- text-align: center;
807
- display: block;
808
- background: none;
809
- border: none;
810
- width: 100%;
811
- font-family: inherit;
812
- padding: 0;
813
- appearance: none;
814
- -webkit-appearance: none;
815
- -webkit-tap-highlight-color: transparent;
816
- box-shadow: none;
817
- outline: none;
818
- }
819
- .__crossx-skip-btn:hover,
820
- .__crossx-skip-btn:focus,
821
- .__crossx-skip-btn:active {
822
- background: none !important;
823
- color: var(--cx-subtitle) !important;
824
- opacity: 1 !important;
825
- box-shadow: none !important;
826
- outline: none !important;
827
- filter: none !important;
828
- transform: none !important;
829
- text-decoration: underline !important;
830
- }
831
-
832
- /* ── PIN Input Modal ───────────────────────────────────────────── */
833
- .__crossx-pin-center {
834
- display: flex;
835
- flex-direction: column;
836
- align-items: center;
837
- justify-content: center;
838
- height: 272px;
839
- gap: 16px;
840
- padding: 20px 64px 24px;
841
- }
842
- .__crossx-pin-inputs {
843
- display: flex;
844
- gap: 16px;
845
- }
846
- .__crossx-pin-input {
847
- width: 72px;
848
- height: 72px;
849
- border: 1px solid var(--cx-input-border);
850
- border-radius: 8px;
851
- background: var(--cx-input-bg);
852
- text-align: center;
853
- font-size: 32px;
854
- font-weight: 600;
855
- font-family: 'Sora', sans-serif;
856
- color: var(--cx-value);
857
- outline: none;
858
- transition: border-color 0.15s, box-shadow 0.15s;
859
- -webkit-text-security: disc;
860
- }
861
- .__crossx-pin-input:hover:not(:focus) {
862
- border-color: var(--cx-border-medium);
863
- }
864
- .__crossx-pin-input:focus {
865
- border-color: var(--cx-primary);
866
- box-shadow: 0 0 0 2px var(--cx-primary-glow);
867
- }
868
- .__crossx-pin-input.--error {
869
- border-color: var(--cx-error);
870
- }
871
- .__crossx-pin-hint {
872
- font-size: 16px;
873
- font-weight: 500;
874
- line-height: 1.5;
875
- color: var(--cx-subtitle);
876
- text-align: center;
877
- font-family: 'Pretendard', -apple-system, sans-serif;
878
- letter-spacing: -0.16px;
879
- margin: 0;
880
- }
881
- .__crossx-pin-error-text {
882
- font-size: 14px;
883
- font-weight: 500;
884
- line-height: 1.4;
885
- color: var(--cx-error);
886
- text-align: center;
887
- margin: 0;
888
- }
889
- .__crossx-pin-attempt {
890
- font-size: 16px;
891
- font-weight: 500;
892
- line-height: 1.5;
893
- color: var(--cx-error);
894
- text-align: center;
895
- font-family: 'Pretendard', -apple-system, sans-serif;
896
- letter-spacing: -0.16px;
897
- margin: 0;
898
- }
899
- .__crossx-pin-warning {
900
- font-size: 16px;
901
- font-weight: 500;
902
- line-height: 1.5;
903
- color: var(--cx-error);
904
- text-align: center;
905
- font-family: 'Pretendard', -apple-system, sans-serif;
906
- letter-spacing: -0.16px;
907
- margin: 0;
908
- }
909
-
910
- /* ── PIN Lock Modal ─────────────────────────────────────────── */
911
- .__crossx-pin-dot {
912
- width: 68px;
913
- height: 68px;
914
- border-radius: 12px;
915
- background: var(--cx-input-bg);
916
- display: flex;
917
- align-items: center;
918
- justify-content: center;
919
- font-size: 24px;
920
- color: var(--cx-subtitle);
921
- flex-shrink: 0;
922
- }
923
- .__crossx-pin-lock-messages {
924
- display: flex;
925
- flex-direction: column;
926
- gap: 4px;
927
- text-align: center;
928
- width: 100%;
929
- }
930
- .__crossx-pin-lock-message {
931
- font-size: 16px;
932
- font-weight: 500;
933
- line-height: 1.5;
934
- color: var(--cx-error);
935
- font-family: 'Pretendard', -apple-system, sans-serif;
936
- letter-spacing: -0.16px;
937
- margin: 0;
938
- }
939
- .__crossx-pin-lock-secondary {
940
- font-size: 16px;
941
- font-weight: 500;
942
- line-height: 1.5;
943
- color: var(--cx-subtitle);
944
- font-family: 'Pretendard', -apple-system, sans-serif;
945
- letter-spacing: -0.16px;
946
- margin: 0;
947
- }
948
-
949
- /* ── Signature Request modals (message & typed data) ───────── */
950
- .__crossx-sig-subtitle {
951
- font-size: 16px;
952
- font-weight: 600;
953
- line-height: 1.5;
954
- letter-spacing: -0.01em;
955
- color: var(--cx-content-high); /* Figma content/high */
956
- text-align: center;
957
- margin: 0;
958
- }
959
- .__crossx-sig-origin { color: var(--cx-primary); }
960
- .__crossx-addr-pill {
961
- background: var(--cx-pill-bg);
962
- border-radius: 12px;
963
- padding: 16px;
964
- display: flex;
965
- align-items: center;
966
- justify-content: center;
967
- gap: 8px;
968
- color: var(--cx-value);
969
- }
970
- .__crossx-addr-pill-text {
971
- font-size: 18px;
972
- font-weight: 600;
973
- line-height: 1.5;
974
- letter-spacing: -0.01em;
975
- font-family: 'JetBrains Mono', ui-monospace, monospace; /* Figma 주소 = mono */
976
- color: var(--cx-content-high);
977
- }
978
- .__crossx-warning {
979
- font-size: 14px;
980
- font-weight: 400;
981
- line-height: 1.5;
982
- letter-spacing: -0.01em;
983
- color: var(--cx-warning); /* Figma system/orange/high */
984
- text-align: center;
985
- margin: 0;
986
- }
987
- .__crossx-msg-raw {
988
- font-size: 12px;
989
- font-weight: 400;
990
- line-height: 1.5;
991
- letter-spacing: -0.01em;
992
- color: var(--cx-subtitle);
993
- white-space: pre-wrap;
994
- word-break: break-all;
995
- max-height: 200px;
996
- overflow-y: auto;
997
- margin: 0;
998
- }
999
- .__crossx-td-rows {
1000
- display: flex;
1001
- flex-direction: column;
1002
- gap: 12px;
1003
- }
1004
- .__crossx-td-row {
1005
- display: flex;
1006
- align-items: center;
1007
- justify-content: space-between;
1008
- min-height: 21px;
1009
- gap: 20px;
1010
- }
1011
- .__crossx-td-label {
1012
- font-size: 14px;
1013
- font-weight: 500;
1014
- line-height: 1.5;
1015
- letter-spacing: -0.01em;
1016
- color: var(--cx-close); /* Figma content/low */
1017
- flex-shrink: 0;
1018
- }
1019
- .__crossx-td-value {
1020
- font-size: 14px;
1021
- font-weight: 500;
1022
- line-height: 1.5;
1023
- letter-spacing: -0.01em;
1024
- color: var(--cx-subtitle); /* Figma content/medium */
1025
- text-align: right;
1026
- display: flex;
1027
- align-items: center;
1028
- justify-content: flex-end;
1029
- gap: 6px;
1030
- min-width: 0;
1031
- }
1032
-
1033
- /* ── Transaction modals ────────────────────────────────────── */
1034
- .__crossx-tx-subtitle {
1035
- font-size: 16px;
1036
- font-weight: 400;
1037
- line-height: 1.5;
1038
- letter-spacing: -0.01em;
1039
- color: var(--cx-subtitle);
1040
- margin: 0;
1041
- }
1042
- .__crossx-raw-tx {
1043
- background: var(--cx-pill-bg);
1044
- border-radius: 12px;
1045
- padding: 16px;
1046
- font-size: 12px;
1047
- font-weight: 400;
1048
- line-height: 1.5;
1049
- color: var(--cx-label);
1050
- white-space: pre-wrap;
1051
- word-break: break-all;
1052
- max-height: 180px;
1053
- overflow-y: auto;
1054
- margin: 0;
1055
- width: 100%;
1056
- box-sizing: border-box;
1057
- }
1058
- .__crossx-approve-btn {
1059
- width: 100%;
1060
- border: none;
1061
- border-radius: 12px;
1062
- background: var(--cx-primary-gradient);
1063
- color: var(--cx-on-primary);
1064
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1065
- cursor: pointer;
1066
- height: 48px;
1067
- }
1068
- .__crossx-approve-btn:hover,
1069
- .__crossx-approve-btn:focus,
1070
- .__crossx-approve-btn:active {
1071
- opacity: 1 !important;
1072
- box-shadow: none !important;
1073
- outline: none !important;
1074
- filter: none !important;
1075
- transform: none !important;
1076
- background: var(--cx-primary-gradient) !important;
1077
- color: var(--cx-on-primary) !important;
1078
- }
1079
- .__crossx-btn-row {
1080
- display: flex;
1081
- gap: 8px;
1082
- width: 100%;
1083
- }
1084
- .__crossx-cancel-btn {
1085
- flex: 1;
1086
- border: none;
1087
- border-radius: 12px;
1088
- background: var(--cx-pill-bg); /* Figma: 보조 버튼 = surface/medium 채움 */
1089
- color: var(--cx-subtitle);
1090
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1091
- cursor: pointer;
1092
- height: 48px;
1093
- }
1094
- .__crossx-cancel-btn:hover,
1095
- .__crossx-cancel-btn:focus,
1096
- .__crossx-cancel-btn:active {
1097
- opacity: 1 !important;
1098
- box-shadow: none !important;
1099
- outline: none !important;
1100
- filter: none !important;
1101
- transform: none !important;
1102
- background: var(--cx-pill-bg) !important;
1103
- color: var(--cx-subtitle) !important;
1104
- }
1105
- .__crossx-confirm-btn {
1106
- flex: 1;
1107
- border: none;
1108
- border-radius: 12px;
1109
- background: var(--cx-primary-gradient);
1110
- color: var(--cx-on-primary);
1111
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1112
- cursor: pointer;
1113
- height: 48px;
1114
- }
1115
- .__crossx-confirm-btn:hover,
1116
- .__crossx-confirm-btn:focus,
1117
- .__crossx-confirm-btn:active {
1118
- opacity: 1 !important;
1119
- box-shadow: none !important;
1120
- outline: none !important;
1121
- filter: none !important;
1122
- transform: none !important;
1123
- background: var(--cx-primary-gradient) !important;
1124
- color: var(--cx-on-primary) !important;
1125
- }
1126
-
1127
- /* ── Sign/Send modals: max-height + sticky buttons ─────────── */
1128
- .__crossx-card--send-tx,
1129
- .__crossx-card--sign-tx,
1130
- .__crossx-card--sign-msg,
1131
- .__crossx-card--sign-typed {
1132
- display: flex;
1133
- flex-direction: column;
1134
- max-height: 90vh;
1135
- }
1136
- /* sign-tx: col-right-sign이 스크롤 담당, raw-tx는 자연 높이 */
1137
- .__crossx-card--sign-tx .__crossx-col-right-sign {
1138
- flex: 1;
1139
- min-height: 0;
1140
- overflow-y: auto;
1141
- }
1142
- .__crossx-card--sign-tx .__crossx-col-right-sign .__crossx-rows { flex-shrink: 0; }
1143
- .__crossx-card--sign-tx .__crossx-raw-tx { max-height: none; overflow-y: visible; }
1144
- .__crossx-card--send-tx .__crossx-body,
1145
- .__crossx-card--sign-tx .__crossx-body,
1146
- .__crossx-card--sign-msg .__crossx-body,
1147
- .__crossx-card--sign-typed .__crossx-body {
1148
- flex: 1;
1149
- min-height: 0;
1150
- display: flex;
1151
- flex-direction: column;
1152
- overflow: hidden;
1153
- }
1154
- .__crossx-card--send-tx .__crossx-body-cols,
1155
- .__crossx-card--sign-tx .__crossx-body-cols,
1156
- .__crossx-card--sign-msg .__crossx-body-cols,
1157
- .__crossx-card--sign-typed .__crossx-body-cols {
1158
- flex: 1;
1159
- min-height: 0;
1160
- overflow-y: auto;
1161
- }
1162
- .__crossx-card--send-tx .__crossx-btn-row,
1163
- .__crossx-card--sign-tx .__crossx-btn-row,
1164
- .__crossx-card--sign-msg .__crossx-btn-row,
1165
- .__crossx-card--sign-typed .__crossx-btn-row,
1166
- .__crossx-card--send-tx .__crossx-body > .__crossx-approve-btn,
1167
- .__crossx-card--sign-tx .__crossx-body > .__crossx-approve-btn,
1168
- .__crossx-card--sign-msg .__crossx-body > .__crossx-approve-btn,
1169
- .__crossx-card--sign-typed .__crossx-body > .__crossx-approve-btn {
1170
- flex-shrink: 0;
1171
- }
1172
-
1173
- /* ── Transaction Progress / Complete Modal ─────────────────── */
1174
- @keyframes __crossx-spinner {
1175
- to { transform: rotate(360deg); }
1176
- }
1177
- .__crossx-progress-center {
1178
- display: flex;
1179
- flex-direction: column;
1180
- align-items: center;
1181
- justify-content: center;
1182
- gap: 16px;
1183
- padding: 24px 0;
1184
- min-height: 280px;
1185
- }
1186
- .__crossx-spinner {
1187
- width: 48px;
1188
- height: 48px;
1189
- border: 4px solid var(--cx-border);
1190
- border-top-color: var(--cx-primary);
1191
- border-radius: 50%;
1192
- animation: __crossx-spinner 0.8s linear infinite;
1193
- }
1194
- .__crossx-progress-text {
1195
- font-size: 14px;
1196
- font-weight: 400;
1197
- line-height: 1.5;
1198
- color: var(--cx-label);
1199
- text-align: center;
1200
- margin: 0;
1201
- }
1202
- .__crossx-total-pill {
1203
- background: var(--cx-pill-bg);
1204
- border-radius: 12px;
1205
- padding: 16px;
1206
- display: flex;
1207
- align-items: center;
1208
- justify-content: space-between;
1209
- gap: 8px;
1210
- }
1211
- .__crossx-total-label {
1212
- font-size: 14px;
1213
- font-weight: 600;
1214
- line-height: 1.5;
1215
- color: var(--cx-close);
1216
- }
1217
- .__crossx-total-amount {
1218
- font-size: 16px;
1219
- font-weight: 600;
1220
- line-height: 1.3;
1221
- color: var(--cx-pill-amt);
1222
- text-align: right;
1223
- white-space: nowrap;
1224
- flex-shrink: 0;
1225
- }
1226
-
1227
- /* ── Login Selector Modal ──────────────────────────────────── */
1228
- .__crossx-card--login .__crossx-body {
1229
- padding-top: 24px;
1230
- }
1231
- .__crossx-login-btn-row {
1232
- display: flex;
1233
- gap: 8px;
1234
- width: 100%;
1235
- }
1236
- .__crossx-login-btn {
1237
- flex: 1;
1238
- display: flex;
1239
- flex-direction: column;
1240
- gap: 8px;
1241
- padding: 16px;
1242
- background: var(--cx-pill-bg);
1243
- border: none;
1244
- border-radius: 12px;
1245
- cursor: pointer;
1246
- align-items: center;
1247
- justify-content: center;
1248
- appearance: none;
1249
- -webkit-appearance: none;
1250
- -webkit-tap-highlight-color: transparent;
1251
- box-shadow: none;
1252
- outline: none;
1253
- min-width: 0;
1254
- }
1255
- .__crossx-login-btn {
1256
- transition: background-color 0.15s ease, transform 0.1s ease;
1257
- }
1258
- /* 호스트 CSS 간섭 차단(기존 reset) — 상태별 배경·스케일은 아래에서 다시 지정 */
1259
- .__crossx-login-btn:hover,
1260
- .__crossx-login-btn:focus,
1261
- .__crossx-login-btn:active {
1262
- opacity: 1 !important;
1263
- box-shadow: none !important;
1264
- outline: none !important;
1265
- filter: none !important;
1266
- transform: none !important;
1267
- background: var(--cx-pill-bg) !important;
1268
- }
1269
- /* 호버: 한 단계 밝은 표면 (터치 기기는 hover 가 남지 않도록 제외) */
1270
- @media (hover: hover) {
1271
- .__crossx-login-btn:hover {
1272
- background: var(--cx-surface-high) !important;
1273
- }
1274
- }
1275
- /* 프레스: 표면 + 살짝 눌림 */
1276
- .__crossx-login-btn:active {
1277
- background: var(--cx-surface-high) !important;
1278
- transform: scale(0.98) !important;
1279
- }
1280
- .__crossx-login-btn:focus-visible {
1281
- outline: 2px solid var(--cx-primary) !important;
1282
- outline-offset: 2px;
1283
- }
1284
- .__crossx-login-btn-label {
1285
- font-size: 14px;
1286
- font-weight: 600;
1287
- line-height: 1.5;
1288
- letter-spacing: -0.01em;
1289
- color: var(--cx-content-high);
1290
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1291
- text-align: center;
1292
- white-space: nowrap;
1293
- }
1294
- .__crossx-login-icon {
1295
- width: 32px;
1296
- height: 32px;
1297
- flex-shrink: 0;
1298
- display: flex;
1299
- align-items: center;
1300
- justify-content: center;
1301
- }
1302
- .__crossx-login-terms {
1303
- font-size: 12px;
1304
- font-weight: 400;
1305
- line-height: 1.5;
1306
- letter-spacing: -0.01em;
1307
- color: var(--cx-subtitle);
1308
- text-align: center;
1309
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1310
- margin: 0;
1311
- width: 100%;
1312
- }
1313
- /* Figma: 본문은 Content/medium(--cx-subtitle), 링크는 한 단계 진한 본문색 + 상시 밑줄 */
1314
- .__crossx-login-terms-link {
1315
- color: var(--cx-content-high);
1316
- text-decoration: underline;
1317
- text-underline-position: from-font;
1318
- }
1319
- .__crossx-login-terms-link:hover,
1320
- .__crossx-login-terms-link:focus,
1321
- .__crossx-login-terms-link:active {
1322
- color: var(--cx-content-high) !important;
1323
- text-decoration: underline !important;
1324
- opacity: 1 !important;
1325
- background: none !important;
1326
- box-shadow: none !important;
1327
- outline: none !important;
1328
- filter: none !important;
1329
- transform: none !important;
1330
- }
1331
-
1332
- /* ── Connect Other Wallets (Login Selector) ───────────────── */
1333
- .__crossx-login-or-divider {
1334
- display: flex;
1335
- align-items: center;
1336
- gap: 16px;
1337
- width: 100%;
1338
- }
1339
- .__crossx-login-or-divider hr {
1340
- flex: 1;
1341
- border: none;
1342
- border-top: 1px solid var(--cx-border);
1343
- margin: 0;
1344
- }
1345
- .__crossx-login-or-divider span {
1346
- font-size: 16px;
1347
- font-weight: 400;
1348
- line-height: 1.3;
1349
- color: var(--cx-hint);
1350
- font-family: 'Sora', 'Pretendard', -apple-system, sans-serif;
1351
- white-space: nowrap;
1352
- flex-shrink: 0;
1353
- }
1354
- .__crossx-connect-other-block {
1355
- display: flex;
1356
- flex-direction: column;
1357
- width: 100%;
1358
- padding: 16px;
1359
- background: var(--cx-pill-bg);
1360
- border: 1px solid var(--cx-border);
1361
- border-radius: 20px;
1362
- box-sizing: border-box;
1363
- box-shadow: none;
1364
- }
1365
- button.__crossx-connect-other-block {
1366
- cursor: pointer;
1367
- font: inherit;
1368
- text-align: left;
1369
- appearance: none;
1370
- -webkit-appearance: none;
1371
- -webkit-tap-highlight-color: transparent;
1372
- outline: none;
1373
- min-width: 0;
1374
- }
1375
- button.__crossx-connect-other-block::-moz-focus-inner {
1376
- border: 0;
1377
- }
1378
- button.__crossx-connect-other-block:hover,
1379
- button.__crossx-connect-other-block:focus,
1380
- button.__crossx-connect-other-block:active {
1381
- opacity: 1 !important;
1382
- box-shadow: none !important;
1383
- outline: none !important;
1384
- filter: none !important;
1385
- transform: none !important;
1386
- background: var(--cx-pill-bg) !important;
1387
- }
1388
- .__crossx-connect-other-text {
1389
- display: flex;
1390
- flex: 1;
1391
- flex-direction: column;
1392
- align-items: flex-start;
1393
- justify-content: center;
1394
- gap: 6px;
1395
- min-width: 0;
1396
- width: 100%;
1397
- }
1398
- .__crossx-connect-other-wallet-desc-part {
1399
- display: inline-flex;
1400
- align-items: center;
1401
- gap: 6px;
1402
- vertical-align: middle;
1403
- user-select: none;
1404
- -webkit-user-select: none;
1405
- }
1406
- .__crossx-connect-other-wallet-icon {
1407
- display: inline-flex;
1408
- flex-shrink: 0;
1409
- line-height: 0;
1410
- }
1411
- .__crossx-connect-other-wallet-icon svg {
1412
- display: block;
1413
- width: 16px;
1414
- height: 16px;
1415
- }
1416
- .__crossx-connect-other-title {
1417
- font-size: 18px;
1418
- font-weight: 700;
1419
- line-height: 1.3;
1420
- color: var(--cx-value);
1421
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1422
- text-align: left;
1423
- }
1424
- .__crossx-connect-other-desc {
1425
- font-size: 14px;
1426
- font-weight: 400;
1427
- line-height: 1.45;
1428
- color: var(--cx-subtitle);
1429
- font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
1430
- text-align: left;
1431
- }
1432
- .__crossx-connect-other-summary {
1433
- display: block;
1434
- margin: 0;
1435
- width: 100%;
1436
- }
1437
- /* ── Wallet Selector Modal ─────────────────────────────────── */
1438
- .__crossx-overlay--wallet-selector {
1439
- background: rgba(0,0,0,0.7) !important;
1440
- -webkit-backdrop-filter: blur(3.5px);
1441
- backdrop-filter: blur(3.5px);
1442
- }
1443
- .__crossx-card--wallet-selector {
1444
- width: 540px;
1445
- max-width: calc(100vw - 32px);
1446
- max-height: 90vh;
1447
- display: flex;
1448
- flex-direction: column;
1449
- overflow: hidden;
1450
- background: var(--cx-bg);
1451
- border: 1px solid var(--cx-border-medium); /* Figma border/medium */
1452
- border-radius: 24px;
1453
- box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
1454
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1455
- }
1456
- .__crossx-card--wallet-selector .__crossx-header {
1457
- display: flex;
1458
- align-items: flex-start;
1459
- justify-content: space-between;
1460
- gap: 12px;
1461
- padding: 24px;
1462
- flex-shrink: 0;
1463
- }
1464
- .__crossx-card--wallet-selector > .__crossx-divider {
1465
- border-top-color: var(--cx-border);
1466
- flex-shrink: 0;
1467
- }
1468
- .__crossx-wallet-sheet-handle {
1469
- display: none;
1470
- }
1471
- .__crossx-wallet-header-copy {
1472
- display: flex;
1473
- flex: 1;
1474
- min-width: 0;
1475
- flex-direction: column;
1476
- gap: 4px;
1477
- padding-right: 16px;
1478
- }
1479
- .__crossx-card--wallet-selector .__crossx-title {
1480
- margin: 0;
1481
- padding-right: 0;
1482
- color: var(--cx-title);
1483
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1484
- font-size: 20px;
1485
- font-weight: 600;
1486
- line-height: 1.25;
1487
- letter-spacing: 0;
1488
- white-space: nowrap;
1489
- }
1490
- .__crossx-card--wallet-selector .__crossx-subtitle--body {
1491
- margin: 0;
1492
- color: var(--cx-subtitle);
1493
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1494
- font-size: 14px;
1495
- font-weight: 400;
1496
- line-height: 1.5;
1497
- letter-spacing: -0.01em;
1498
- }
1499
- .__crossx-card--wallet-selector .__crossx-close {
1500
- position: static;
1501
- width: 24px;
1502
- height: 24px;
1503
- flex-shrink: 0;
1504
- border-radius: 0;
1505
- }
1506
- .__crossx-card--wallet-selector .__crossx-close svg {
1507
- width: 24px;
1508
- height: 24px;
1509
- }
1510
- .__crossx-wallet-selector-body {
1511
- flex: 1;
1512
- min-height: 0;
1513
- overflow-y: auto;
1514
- padding: 0;
1515
- gap: 0;
1516
- }
1517
- .__crossx-wallet-list-section {
1518
- display: flex;
1519
- flex-direction: column;
1520
- gap: 8px;
1521
- width: 100%;
1522
- padding: 24px 24px 12px;
1523
- box-sizing: border-box;
1524
- }
1525
- .__crossx-wallet-help-section {
1526
- width: 100%;
1527
- padding: 12px 24px 24px;
1528
- box-sizing: border-box;
1529
- }
1530
- .__crossx-wallet-list {
1531
- display: flex;
1532
- flex-direction: column;
1533
- gap: 8px;
1534
- max-height: 320px;
1535
- overflow-y: auto;
1536
- -webkit-overflow-scrolling: touch;
1537
- overscroll-behavior: contain;
1538
- touch-action: pan-y;
1539
- scrollbar-width: thin;
1540
- scrollbar-color: var(--cx-divider) transparent;
1541
- }
1542
- .__crossx-wallet-list::-webkit-scrollbar {
1543
- width: 4px;
1544
- background: transparent;
1545
- }
1546
- .__crossx-wallet-list::-webkit-scrollbar-track {
1547
- background: transparent;
1548
- }
1549
- .__crossx-wallet-list::-webkit-scrollbar-thumb {
1550
- background: var(--cx-divider);
1551
- border-radius: 2px;
1552
- }
1553
- .__crossx-wallet-item {
1554
- display: flex;
1555
- align-items: center;
1556
- justify-content: space-between;
1557
- gap: 8px;
1558
- min-height: 66px;
1559
- padding: 12px 16px;
1560
- background: var(--cx-pill-bg);
1561
- border: none;
1562
- border-radius: 12px;
1563
- cursor: pointer;
1564
- appearance: none;
1565
- -webkit-appearance: none;
1566
- -webkit-tap-highlight-color: transparent;
1567
- box-shadow: none;
1568
- outline: none;
1569
- width: 100%;
1570
- text-align: left;
1571
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1572
- transition: background-color 0.15s ease, transform 0.1s ease;
1573
- }
1574
- .__crossx-wallet-item--selected {
1575
- border-color: transparent;
1576
- }
1577
- .__crossx-wallet-item:hover {
1578
- background: var(--cx-surface-high);
1579
- }
1580
- .__crossx-wallet-item:active {
1581
- background: var(--cx-surface-high);
1582
- transform: scale(0.985);
1583
- }
1584
- .__crossx-wallet-item:focus-visible {
1585
- outline: 2px solid var(--cx-primary);
1586
- outline-offset: 2px;
1587
- }
1588
- .__crossx-wallet-avatar {
1589
- width: 28px;
1590
- height: 28px;
1591
- flex-shrink: 0;
1592
- border-radius: 50%;
1593
- overflow: hidden;
1594
- display: flex;
1595
- align-items: center;
1596
- justify-content: center;
1597
- background: transparent;
1598
- }
1599
- .__crossx-wallet-avatar-img {
1600
- width: 28px;
1601
- height: 28px;
1602
- object-fit: cover;
1603
- display: block;
1604
- }
1605
- .__crossx-wallet-avatar-fallback {
1606
- width: 100%;
1607
- height: 100%;
1608
- display: none;
1609
- align-items: center;
1610
- justify-content: center;
1611
- }
1612
- .__crossx-wallet-avatar-fallback svg {
1613
- width: 100%;
1614
- height: 100%;
1615
- display: block;
1616
- }
1617
- .__crossx-wallet-info {
1618
- display: flex;
1619
- flex-direction: column;
1620
- align-items: flex-start;
1621
- gap: 0;
1622
- min-width: 0;
1623
- flex: 1;
1624
- }
1625
- .__crossx-wallet-idx {
1626
- font-size: 16px;
1627
- font-weight: 600;
1628
- line-height: 1.5;
1629
- color: var(--cx-content-high); /* Figma content/high */
1630
- letter-spacing: -0.01em;
1631
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1632
- white-space: nowrap;
1633
- overflow: hidden;
1634
- text-overflow: ellipsis;
1635
- max-width: 100%;
1636
- }
1637
- .__crossx-wallet-addr {
1638
- font-size: 12px;
1639
- font-weight: 400;
1640
- line-height: 1.5;
1641
- color: var(--cx-subtitle);
1642
- letter-spacing: -0.01em;
1643
- font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
1644
- white-space: nowrap;
1645
- }
1646
- .__crossx-wallet-selected {
1647
- display: none;
1648
- }
1649
- .__crossx-wallet-check {
1650
- display: flex;
1651
- flex-shrink: 0;
1652
- margin-left: auto;
1653
- width: 20px;
1654
- height: 20px;
1655
- align-items: center;
1656
- justify-content: center;
1657
- }
1658
- .__crossx-wallet-check svg {
1659
- width: 20px;
1660
- height: 20px;
1661
- }
1662
- .__crossx-wallet-add {
1663
- display: flex;
1664
- align-items: center;
1665
- justify-content: center;
1666
- gap: 8px;
1667
- padding: 15px 16px; /* Figma 높이 56 (보더 1px 포함) */
1668
- border: 1px dashed var(--cx-border-medium); /* Figma border/medium */
1669
- border-radius: 12px;
1670
- cursor: pointer;
1671
- appearance: none;
1672
- -webkit-appearance: none;
1673
- -webkit-tap-highlight-color: transparent;
1674
- box-shadow: none;
1675
- outline: none;
1676
- background: none;
1677
- width: 100%;
1678
- flex-shrink: 0;
1679
- color: var(--cx-value);
1680
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1681
- transition: background-color 0.15s ease, border-color 0.15s ease, transform 0.1s ease;
1682
- }
1683
- .__crossx-wallet-add:hover:not(:disabled) {
1684
- background: var(--cx-pill-bg);
1685
- }
1686
- .__crossx-wallet-add:active:not(:disabled) {
1687
- background: var(--cx-surface-high);
1688
- transform: scale(0.99);
1689
- }
1690
- .__crossx-wallet-add:focus-visible {
1691
- outline: 2px solid var(--cx-primary);
1692
- outline-offset: 2px;
1693
- }
1694
- .__crossx-wallet-add:disabled { opacity: 0.5; cursor: not-allowed; }
1695
- .__crossx-wallet-add-icon {
1696
- width: 24px;
1697
- height: 24px;
1698
- color: var(--cx-label);
1699
- }
1700
- .__crossx-wallet-add-label {
1701
- font-size: 16px;
1702
- font-weight: 500;
1703
- line-height: 1.5;
1704
- letter-spacing: -0.01em;
1705
- color: var(--cx-content-high); /* Figma content/high */
1706
- }
1707
- .__crossx-wallet-empty {
1708
- margin: 0;
1709
- padding: 16px;
1710
- border-radius: 12px;
1711
- background: var(--cx-pill-bg);
1712
- color: var(--cx-subtitle);
1713
- font-size: 14px;
1714
- line-height: 1.5;
1715
- text-align: center;
1716
- word-break: keep-all;
1717
- }
1718
- .__crossx-wallet-add-error {
1719
- margin: 8px 0 0;
1720
- padding: 8px 10px;
1721
- font-size: 13px;
1722
- line-height: 1.45;
1723
- color: var(--cx-error);
1724
- background: color-mix(in srgb, var(--cx-error) 10%, transparent);
1725
- border: 1px solid color-mix(in srgb, var(--cx-error) 35%, transparent);
1726
- border-radius: 8px;
1727
- word-break: break-word;
1728
- }
1729
- .__crossx-wallet-add-error[hidden] { display: none; }
1730
- .__crossx-wallet-help-section .__crossx-mig-info {
1731
- gap: 6px;
1732
- padding: 12px;
1733
- background: var(--cx-pill-bg);
1734
- border: 1px solid var(--cx-border);
1735
- border-radius: 12px;
1736
- box-sizing: border-box;
1737
- }
1738
- .__crossx-wallet-help-section .__crossx-mig-info-title {
1739
- color: var(--cx-content-high); /* Figma content/high */
1740
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1741
- font-size: 14px;
1742
- font-weight: 600;
1743
- line-height: 1.5;
1744
- letter-spacing: -0.01em;
1745
- }
1746
- .__crossx-wallet-help-section .__crossx-mig-info-desc {
1747
- color: var(--cx-subtitle);
1748
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1749
- font-size: 12px;
1750
- font-weight: 400;
1751
- line-height: 1.5;
1752
- letter-spacing: -0.01em;
1753
- }
1754
-
1755
- /* ── Safe area fill (mobile only, created by JS in mountOverlay) ── */
1756
- .__crossx-safe-area-fill {
1757
- display: none;
1758
- }
1759
- /* ── Mobile bottom sheet ───────────────────────────────────── */
1760
- /* ── 서명·전송 모달: Figma 「트랜잭션모달」 ──────────────────────────
1761
- 폭 480, 본문 패딩 24 · 간격 24, 서브타이틀↔주소 24 · 주소↔경고 12, 마지막 행↔버튼 36(24+12).
1762
- 모바일은 뒤의 \`.__crossx-card { width: 100% }\` 가, 가로 게임 화면은 아래 media 제외로 기존 규칙이 유지된다. */
1763
- .__crossx-card--sign-tx,
1764
- .__crossx-card--sign-msg,
1765
- .__crossx-card--sign-typed,
1766
- .__crossx-card--send-tx {
1767
- width: 480px;
1768
- }
1769
- @media not all and (orientation: landscape) and (max-height: 500px) {
1770
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-title {
1771
- margin-bottom: 0;
1772
- }
1773
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-body {
1774
- padding-top: 24px;
1775
- }
1776
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-body-cols {
1777
- gap: 24px;
1778
- }
1779
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-col-left {
1780
- gap: 24px;
1781
- }
1782
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-addr-pill + .__crossx-warning {
1783
- margin-top: -12px;
1784
- }
1785
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-btn-row {
1786
- margin-top: 20px;
1787
- }
1788
- /* 단일 확인 버튼(전송 승인 등)도 마지막 블록과 36(24+12) */
1789
- :is(.__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx) .__crossx-body > .__crossx-approve-btn {
1790
- margin-top: 20px;
1791
- }
1792
- /* 전송 승인: 안내 문구 ↔ 상세 24 */
1793
- .__crossx-card--send-tx .__crossx-tx-subtitle {
1794
- margin-bottom: 8px;
1795
- }
1796
- }
1797
- /* 주소 pill 지갑 아이콘 — Figma 20 · content/medium */
1798
- .__crossx-addr-pill > svg {
1799
- width: 20px;
1800
- height: 20px;
1801
- flex-shrink: 0;
1802
- color: var(--cx-subtitle);
1803
- }
1804
- /* Figma lucide/copy 16 */
1805
- .__crossx-row-value .__crossx-copy-btn svg,
1806
- .__crossx-td-value .__crossx-copy-btn svg {
1807
- width: 16px;
1808
- height: 16px;
1809
- }
1810
-
1811
- /* ── CTA 버튼 텍스트 세로 중앙 고정 ─────────────────────────────
1812
- 높이만 지정한 버튼(.__crossx-pw-btn, .__crossx-wallet-created-btn)은 호스트 페이지의
1813
- 전역 \`button { padding }\` 이 새어 들어와 텍스트가 아래로 밀렸다(예: 15px 30px → 3px 처짐).
1814
- 모든 CTA 를 flex 중앙 정렬 + 대칭 패딩으로 고정해 호스트 CSS 와 무관하게 가운데에 둔다. */
1815
- /* 모든 CTA 공통 규격(단일 출처): 가운데 정렬 · 높이 48 · 좌우 16 · 16/600 · 줄높이 1.5 */
1816
- .__crossx-pw-btn,
1817
- .__crossx-wallet-created-btn,
1818
- .__crossx-pin6-next,
1819
- .__crossx-approve-btn,
1820
- .__crossx-confirm-btn,
1821
- .__crossx-cancel-btn {
1822
- display: flex;
1823
- align-items: center;
1824
- justify-content: center;
1825
- box-sizing: border-box;
1826
- text-align: center;
1827
- height: 48px;
1828
- padding: 0 16px;
1829
- font-size: 16px;
1830
- font-weight: 600;
1831
- line-height: 1.5;
1832
- }
1833
-
1834
- @media (max-width: 480px) {
1835
- #${Y} {
1836
- align-items: flex-end;
1837
- /*
1838
- * iOS Safari 는 soft keyboard 가 떠도 layout viewport 를 축소시키지 않아
1839
- * \`position: fixed; inset: 0\` 인 overlay 의 하단 docking card 가 키보드에
1840
- * 가려집니다. mountOverlay 의 visualViewport listener 가 매 resize 마다
1841
- * layoutH - visualBottom 을 \`--cx-keyboard-inset\` 으로 publish 하므로,
1842
- * 여기서 padding-bottom 으로 받아 카드 정렬축을 키보드 위로 끌어올립니다.
1843
- * 키보드 닫히면 inset=0 으로 자동 복귀.
1844
- */
1845
- padding-bottom: var(--cx-keyboard-inset, 0px);
1846
- }
1847
- .__crossx-safe-area-fill {
1848
- display: block;
1849
- position: fixed;
1850
- bottom: 0;
1851
- left: 0;
1852
- right: 0;
1853
- height: calc(env(safe-area-inset-bottom, 0px) + 16px);
1854
- min-height: 16px;
1855
- pointer-events: none;
1856
- z-index: 2147483646;
1857
- }
1858
- .__crossx-card {
1859
- width: 100%;
1860
- max-width: 100%;
1861
- border-radius: 24px 24px 0 0;
1862
- border-bottom: none;
1863
- box-sizing: border-box;
1864
- max-height: 85vh;
1865
- overflow-y: auto;
1866
- padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 16px);
1867
- animation: __crossx-slide-up-mobile 0.25s ease;
1868
- }
1869
- .__crossx-card--wallet-selector {
1870
- overflow: hidden !important;
1871
- display: flex !important;
1872
- flex-direction: column !important;
1873
- border: 1px solid var(--cx-border-medium) !important; /* Figma border/medium */
1874
- border-bottom: none !important;
1875
- border-radius: 24px 24px 0 0 !important;
1876
- max-height: 85vh;
1877
- padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 20px);
1878
- }
1879
- .__crossx-card--wallet-selector .__crossx-header {
1880
- flex-shrink: 0;
1881
- flex-direction: column;
1882
- align-items: center;
1883
- gap: 16px;
1884
- padding: 16px;
1885
- }
1886
- .__crossx-card--wallet-selector > .__crossx-divider { flex-shrink: 0; }
1887
- .__crossx-wallet-sheet-handle {
1888
- display: block;
1889
- width: 30px;
1890
- height: 6px;
1891
- border-radius: 9999px;
1892
- background: var(--cx-surface-subtle);
1893
- flex-shrink: 0;
1894
- }
1895
- .__crossx-wallet-header-copy {
1896
- width: 100%;
1897
- padding-right: 0;
1898
- }
1899
- .__crossx-card--wallet-selector .__crossx-close {
1900
- display: none;
1901
- }
1902
- .__crossx-card--wallet-selector .__crossx-body,
1903
- .__crossx-card--wallet-selector .__crossx-wallet-selector-body {
1904
- flex: 1;
1905
- min-height: 0;
1906
- overflow-y: auto;
1907
- display: flex;
1908
- flex-direction: column;
1909
- }
1910
- .__crossx-wallet-list-section { padding: 24px 16px 12px; }
1911
- .__crossx-wallet-help-section { padding: 12px 16px 16px; }
1912
- .__crossx-card--wallet-selector .__crossx-wallet-list {
1913
- max-height: 203px;
1914
- }
1915
- .__crossx-card--wallet-created {
1916
- width: 100% !important;
1917
- max-width: 100% !important;
1918
- border-radius: 24px 24px 0 0 !important;
1919
- border: 1px solid var(--cx-border-medium) !important;
1920
- border-bottom: none !important;
1921
- padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 20px);
1922
- }
1923
- .__crossx-card--wallet-created .__crossx-header {
1924
- display: flex;
1925
- flex-direction: column;
1926
- align-items: center;
1927
- gap: 16px;
1928
- padding: 16px;
1929
- border-bottom: 1px solid var(--cx-border);
1930
- }
1931
- .__crossx-card--wallet-created .__crossx-title {
1932
- width: 100%;
1933
- padding-right: 0 !important;
1934
- }
1935
- .__crossx-card--wallet-created .__crossx-close {
1936
- display: none;
1937
- }
1938
- /* 헤더 border-bottom 이 구분선 역할 — hr 까지 보이면 선이 두 줄 */
1939
- .__crossx-card--wallet-created > .__crossx-divider { display: none; }
1940
- /* 기본 규칙(뒤에 선언)보다 우선하도록 카드 클래스를 앞에 붙인다 */
1941
- .__crossx-card--wallet-created .__crossx-wallet-created-sheet-handle {
1942
- display: block;
1943
- width: 30px;
1944
- height: 6px;
1945
- border-radius: 9999px;
1946
- background: var(--cx-surface-high);
1947
- flex-shrink: 0;
1948
- }
1949
- .__crossx-card--wallet-created .__crossx-wallet-created-body {
1950
- padding: 20px 16px;
1951
- }
1952
- .__crossx-card--wallet-created .__crossx-wallet-created-hero {
1953
- height: 285px;
1954
- }
1955
- .__crossx-card--wallet-created .__crossx-wallet-created-footer {
1956
- padding: 12px 16px 16px;
1957
- }
1958
- .__crossx-card--send-tx,
1959
- .__crossx-card--sign-tx,
1960
- .__crossx-card--sign-msg,
1961
- .__crossx-card--sign-typed {
1962
- overflow: hidden !important;
1963
- display: flex !important;
1964
- flex-direction: column !important;
1965
- }
1966
- .__crossx-card--send-tx .__crossx-body,
1967
- .__crossx-card--sign-tx .__crossx-body,
1968
- .__crossx-card--sign-msg .__crossx-body,
1969
- .__crossx-card--sign-typed .__crossx-body {
1970
- flex: 1;
1971
- min-height: 0;
1972
- overflow-y: auto;
1973
- -webkit-overflow-scrolling: touch;
1974
- }
1975
- .__crossx-card--send-tx .__crossx-btn-row,
1976
- .__crossx-card--sign-tx .__crossx-btn-row,
1977
- .__crossx-card--sign-msg .__crossx-btn-row,
1978
- .__crossx-card--sign-typed .__crossx-btn-row,
1979
- .__crossx-card--send-tx .__crossx-body > .__crossx-approve-btn,
1980
- .__crossx-card--sign-tx .__crossx-body > .__crossx-approve-btn,
1981
- .__crossx-card--sign-msg .__crossx-body > .__crossx-approve-btn,
1982
- .__crossx-card--sign-typed .__crossx-body > .__crossx-approve-btn {
1983
- flex-shrink: 0;
1984
- }
1985
- .__crossx-login-btn-row {
1986
- flex-direction: column;
1987
- }
1988
- /* 모바일: 버튼은 세로로 쌓고, 버튼 안은 아이콘+텍스트 가로 정렬(가운데) */
1989
- .__crossx-login-btn {
1990
- flex-direction: row;
1991
- gap: 8px;
1992
- }
1993
- .__crossx-login-icon {
1994
- width: 28px;
1995
- height: 28px;
1996
- }
1997
- .__crossx-login-icon svg {
1998
- width: 28px;
1999
- height: 28px;
2000
- }
2001
- .__crossx-login-btn-label {
2002
- font-size: 16px;
2003
- }
2004
- .__crossx-login-btn-label {
2005
- white-space: normal;
2006
- }
2007
- .__crossx-card--login .__crossx-body {
2008
- padding: 16px;
2009
- }
2010
- /* Figma 모바일 시트 헤더: 손잡이 + 여백 16, X 없음(배경 탭·Esc 로 닫힘) */
2011
- .__crossx-card--login .__crossx-header {
2012
- display: flex;
2013
- flex-direction: column;
2014
- align-items: center;
2015
- gap: 16px;
2016
- padding: 16px;
2017
- }
2018
- .__crossx-card--login .__crossx-login-sheet-handle {
2019
- display: block;
2020
- width: 30px;
2021
- height: 6px;
2022
- border-radius: 9999px;
2023
- background: var(--cx-surface-high);
2024
- flex-shrink: 0;
2025
- }
2026
- .__crossx-card--login .__crossx-login-title-wrap {
2027
- width: 100%;
2028
- padding-right: 0 !important;
2029
- }
2030
- .__crossx-card--login .__crossx-close { display: none; }
2031
- /* ── 모든 모달 모바일 시트 헤더 통일 (로그인·PIN·지갑 생성과 같은 방식) ──
2032
- 손잡이(30×6) + 여백 16, 우상단 X 숨김. 손잡이는 ::before 로 그려 마크업을 바꾸지 않는다.
2033
- 닫기는 배경 탭(백드롭)·본문 버튼으로 가능하다. 비밀번호 화면(--password)은 X 외 취소 수단이
2034
- 없어 제외한다. 로그인·PIN·지갑 생성·지갑 선택은 자체 손잡이가 있어 제외. */
2035
- :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header {
2036
- display: flex;
2037
- flex-direction: column;
2038
- align-items: stretch;
2039
- padding: 16px;
2040
- }
2041
- :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header::before {
2042
- content: '';
2043
- align-self: center;
2044
- width: 30px;
2045
- height: 6px;
2046
- margin-bottom: 16px;
2047
- border-radius: 9999px;
2048
- background: var(--cx-surface-high);
2049
- flex-shrink: 0;
2050
- }
2051
- :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header > .__crossx-close { display: none; }
2052
- :is(.__crossx-card--migration, .__crossx-card--sign-tx, .__crossx-card--sign-msg, .__crossx-card--sign-typed, .__crossx-card--send-tx):not(.__crossx-card--login) > .__crossx-header .__crossx-title { padding-right: 0 !important; }
2053
- /* ── Password card: mobile bottom sheet ── */
2054
- .__crossx-card--password {
2055
- width: 100% !important;
2056
- max-width: 100% !important;
2057
- border-radius: 20px 20px 0 0 !important;
2058
- border: 1px solid var(--cx-border) !important;
2059
- border-bottom: none !important;
2060
- max-height: 92vh;
2061
- overflow: hidden;
2062
- display: flex;
2063
- flex-direction: column;
2064
- animation: __crossx-slide-up-mobile 0.25s ease;
2065
- }
2066
- .__crossx-card--password .__crossx-header {
2067
- padding: 16px 20px;
2068
- flex-shrink: 0;
2069
- }
2070
- .__crossx-card--password .__crossx-title {
2071
- font-size: 16px;
2072
- margin-bottom: 0;
2073
- }
2074
- .__crossx-card--password .__crossx-pw-subtitle,
2075
- .__crossx-card--password .__crossx-pw-subtitle--tertiary { display: none; }
2076
- .__crossx-card--password > .__crossx-divider { display: none; }
2077
- .__crossx-card--password .__crossx-pw-body {
2078
- flex: 1;
2079
- min-height: 0;
2080
- overflow-y: auto;
2081
- -webkit-overflow-scrolling: touch;
2082
- padding: 0 20px 20px;
2083
- gap: 16px;
2084
- }
2085
- .__crossx-card--password .__crossx-pw-fields { gap: 16px; }
2086
- .__crossx-card--password .__crossx-pw-notice-title { font-size: 20px; }
2087
- .__crossx-card--password .__crossx-pw-fg--confirm { margin-top: 0; }
2088
- .__crossx-home-indicator { display: flex; }
2089
- /* ── PIN6 모바일 bottom sheet ── */
2090
- .__crossx-card--pin6 {
2091
- width: 100% !important;
2092
- max-width: 100% !important;
2093
- border-radius: 24px 24px 0 0 !important;
2094
- border: 1px solid var(--cx-border-medium) !important;
2095
- border-bottom: none !important;
2096
- max-height: 92vh;
2097
- overflow: hidden;
2098
- display: flex;
2099
- flex-direction: column;
2100
- box-shadow: 0 4px 30px -1px rgba(0,0,0,0.15);
2101
- }
2102
- .__crossx-card--pin6 > .__crossx-divider { display: none; }
2103
- .__crossx-card--pin6 .__crossx-header {
2104
- display: flex;
2105
- flex-direction: column;
2106
- align-items: center;
2107
- gap: 16px;
2108
- padding: 16px;
2109
- flex-shrink: 0;
2110
- border-bottom: 1px solid var(--cx-border);
2111
- }
2112
- .__crossx-card--pin6 .__crossx-title {
2113
- width: 100%;
2114
- font-size: 20px;
2115
- margin-bottom: 0;
2116
- padding-right: 0 !important;
2117
- }
2118
- .__crossx-card--pin6 .__crossx-close { display: none; }
2119
- /* 기본 규칙이 이 media 블록보다 뒤에 선언돼 있어 카드 클래스로 우선순위를 올린다 */
2120
- .__crossx-card--pin6 .__crossx-pin6-sheet-handle {
2121
- display: block;
2122
- width: 30px;
2123
- height: 6px;
2124
- border-radius: 9999px;
2125
- background: var(--cx-surface-high);
2126
- flex-shrink: 0;
2127
- }
2128
- /* Figma: 헤더 부제목 노출 — 제목과 4px 간격(헤더 gap 16 - 12), 좌측 정렬 */
2129
- .__crossx-card--pin6 .__crossx-header .__crossx-pw-subtitle,
2130
- .__crossx-card--pin6 .__crossx-header .__crossx-pin6-header-sub {
2131
- width: 100%;
2132
- margin-top: -12px;
2133
- }
2134
- /* Notice 화면 body (pw-body) — 기본 규칙(뒤에 선언)보다 우선하도록 카드 클래스를 겹친다 */
2135
- .__crossx-card.__crossx-card--pin6 .__crossx-pw-body {
2136
- flex: 1;
2137
- min-height: 0;
2138
- overflow-y: auto;
2139
- -webkit-overflow-scrolling: touch;
2140
- padding: 16px;
2141
- gap: 32px;
2142
- }
2143
- .__crossx-card--pin6 .__crossx-pw-fields--notice {
2144
- flex: 1;
2145
- min-height: 0;
2146
- overflow-y: auto;
2147
- -webkit-overflow-scrolling: touch;
2148
- }
2149
- .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 16px; }
2150
- .__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
2151
- .__crossx-card--pin6 .__crossx-pin6-footer {
2152
- padding: 12px 16px 16px;
2153
- }
2154
- /* Figma 시트: 홈 인디케이터 없이 하단 여백 20 */
2155
- .__crossx-card.__crossx-card--pin6 {
2156
- padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 20px);
2157
- }
2158
- .__crossx-card--pin6 .__crossx-home-indicator { display: none; }
2159
- /* PIN 입력 body */
2160
- .__crossx-card--pin6 .__crossx-pin6-body {
2161
- flex: 1;
2162
- min-height: 0;
2163
- overflow-y: auto;
2164
- -webkit-overflow-scrolling: touch;
2165
- padding: 40px 16px;
2166
- gap: 16px;
2167
- }
2168
- /* PIN 넘패드 활성화 */
2169
- .__crossx-pin6-numpad { display: flex !important; }
2170
- .__crossx-card--pin6 .__crossx-pin6-box { display: none !important; }
2171
- .__crossx-card--pin6 .__crossx-pin6-dots { display: flex !important; }
2172
- /* PIN 키보드 모드: 'native' — OS 기본 숫자 키보드 사용 (numpad 숨기고 input box 노출) */
2173
- .__crossx-card--pin6.--native-keypad .__crossx-pin6-numpad { display: none !important; }
2174
- .__crossx-card--pin6.--native-keypad .__crossx-pin6-box { display: inline-block !important; }
2175
- .__crossx-card--pin6.--native-keypad .__crossx-pin6-dots { display: none !important; }
2176
- .__crossx-home-indicator { display: flex; }
2177
- }
2178
- @keyframes __crossx-slide-up-mobile {
2179
- from { transform: translateY(100%); }
2180
- to { transform: translateY(0); }
2181
- }
2182
-
2183
- /* ── 2-column wrapper (portrait: column, landscape: row) ── */
2184
- .__crossx-body-cols {
2185
- display: flex;
2186
- flex-direction: column;
2187
- gap: 16px;
2188
- width: 100%;
2189
- }
2190
- .__crossx-col-left {
2191
- display: flex;
2192
- flex-direction: column;
2193
- gap: 16px;
2194
- }
2195
- .__crossx-divider--cols { flex-shrink: 0; }
2196
- .__crossx-col-right-ws {
2197
- display: flex;
2198
- flex-direction: column;
2199
- gap: 8px;
2200
- }
2201
- .__crossx-col-right-sign {
2202
- display: flex;
2203
- flex-direction: column;
2204
- gap: 16px;
2205
- }
2206
-
2207
- /* ── Landscape for signing/transaction modals ──────────── */
2208
- @media (orientation: landscape) and (max-height: 500px) {
2209
- #${Y} { align-items: center !important; overflow: hidden; }
2210
- .__crossx-card--send-tx,
2211
- .__crossx-card--sign-tx,
2212
- .__crossx-card--sign-msg,
2213
- .__crossx-card--sign-typed {
2214
- width: 600px;
2215
- max-width: calc(100vw - 32px);
2216
- border-radius: 24px;
2217
- border-bottom: 4px solid var(--cx-border);
2218
- max-height: calc(100vh - 32px);
2219
- overflow: hidden;
2220
- animation: __crossx-slide-up 0.18s ease;
2221
- }
2222
- .__crossx-card--send-tx .__crossx-header,
2223
- .__crossx-card--sign-tx .__crossx-header,
2224
- .__crossx-card--sign-msg .__crossx-header,
2225
- .__crossx-card--sign-typed .__crossx-header {
2226
- padding: 16px 24px 12px;
2227
- }
2228
- .__crossx-card--send-tx .__crossx-body,
2229
- .__crossx-card--sign-tx .__crossx-body,
2230
- .__crossx-card--sign-msg .__crossx-body,
2231
- .__crossx-card--sign-typed .__crossx-body {
2232
- padding: 16px 24px 20px;
2233
- gap: 12px;
2234
- }
2235
- .__crossx-card--send-tx .__crossx-body-cols,
2236
- .__crossx-card--sign-tx .__crossx-body-cols,
2237
- .__crossx-card--sign-msg .__crossx-body-cols,
2238
- .__crossx-card--sign-typed .__crossx-body-cols {
2239
- flex-direction: row;
2240
- gap: 24px;
2241
- align-items: stretch;
2242
- overflow: hidden;
2243
- }
2244
- .__crossx-body-cols > * { flex: 1; min-width: 0; }
2245
- .__crossx-col-left { gap: 8px; }
2246
- .__crossx-divider--cols { display: none; }
2247
- .__crossx-card--send-tx .__crossx-pill {
2248
- flex-direction: column;
2249
- align-items: flex-end;
2250
- }
2251
- .__crossx-card--send-tx .__crossx-col-left,
2252
- .__crossx-card--sign-tx .__crossx-col-left,
2253
- .__crossx-card--sign-msg .__crossx-col-left,
2254
- .__crossx-card--sign-typed .__crossx-col-left,
2255
- .__crossx-card--sign-tx .__crossx-col-right-sign { overflow-y: auto; }
2256
- .__crossx-card--sign-tx .__crossx-col-right-sign .__crossx-rows { flex-shrink: 0; }
2257
- .__crossx-card--sign-tx .__crossx-raw-tx { max-height: none; overflow-y: visible; }
2258
- .__crossx-card--sign-msg .__crossx-msg-raw,
2259
- .__crossx-card--sign-msg .__crossx-msg-box { max-height: none; overflow-y: auto; }
2260
- .__crossx-card--sign-typed .__crossx-td-rows { max-height: none; overflow-y: auto; }
2261
- .__crossx-col-left > .__crossx-divider { display: none; }
2262
- /* ── Password / Notice modal landscape ─────────────────────────── */
2263
- .__crossx-card--password {
2264
- width: 640px;
2265
- max-width: calc(100vw - 32px);
2266
- border-radius: 24px;
2267
- border-bottom: 4px solid var(--cx-border);
2268
- max-height: calc(100vh - 32px);
2269
- overflow: hidden;
2270
- display: flex;
2271
- flex-direction: column;
2272
- }
2273
- .__crossx-card--password .__crossx-header {
2274
- flex-shrink: 0;
2275
- padding: 16px 24px 12px;
2276
- }
2277
- .__crossx-card--password > .__crossx-divider { flex-shrink: 0; }
2278
- .__crossx-card--password .__crossx-pw-body {
2279
- flex: 1;
2280
- min-height: 0;
2281
- overflow: hidden;
2282
- padding: 16px 24px 20px;
2283
- gap: 16px;
2284
- }
2285
- /* Notice: scrollable content, button fixed at bottom */
2286
- .__crossx-card--password .__crossx-pw-fields--notice {
2287
- flex: 1;
2288
- min-height: 0;
2289
- overflow-y: auto;
2290
- -webkit-overflow-scrolling: touch;
2291
- }
2292
- /* Setup & Notice: button pinned at bottom of body */
2293
- .__crossx-card--password .__crossx-pw-body > .__crossx-pw-btn {
2294
- flex-shrink: 0;
2295
- margin-top: 4px;
2296
- }
2297
- /* Create Password: 2-column grid layout */
2298
- .__crossx-card--password .__crossx-pw-fields--setup {
2299
- display: grid;
2300
- grid-template-columns: 1fr 1fr;
2301
- grid-template-areas:
2302
- "new rules"
2303
- "conf rules";
2304
- gap: 16px 24px;
2305
- align-items: start;
2306
- flex: 1;
2307
- min-height: 0;
2308
- overflow-y: auto;
2309
- -webkit-overflow-scrolling: touch;
2310
- }
2311
- .__crossx-card--password .__crossx-pw-fg--new { grid-area: new; }
2312
- .__crossx-card--password .__crossx-pw-fg--confirm { grid-area: conf; margin-top: 0; }
2313
- .__crossx-card--password .__crossx-pw-rules { grid-area: rules; padding-top: 24px; align-self: start; }
2314
- /* Consent / notice modal adjustments */
2315
- .__crossx-card--password .__crossx-pw-notice-title { font-size: 18px; }
2316
- .__crossx-card--password .__crossx-pw-notice-item { padding: 12px 14px; }
2317
-
2318
- /* ── PIN6 랜드스케이프 ─────────────────────────── */
2319
- .__crossx-card--pin6 {
2320
- width: 600px;
2321
- max-width: calc(100vw - 32px);
2322
- border-radius: 24px;
2323
- border: 1px solid var(--cx-border-medium);
2324
- max-height: calc(100vh - 32px);
2325
- overflow: hidden;
2326
- display: flex;
2327
- flex-direction: column;
2328
- animation: __crossx-slide-up 0.18s ease;
2329
- }
2330
- .__crossx-card--pin6 > .__crossx-divider { flex-shrink: 0; }
2331
- .__crossx-card--pin6 .__crossx-header { flex-shrink: 0; padding: 16px; }
2332
- .__crossx-card--pin6 .__crossx-pw-body {
2333
- flex: 1;
2334
- min-height: 0;
2335
- overflow-y: auto;
2336
- -webkit-overflow-scrolling: touch;
2337
- padding: 16px;
2338
- gap: 32px;
2339
- }
2340
- .__crossx-card--pin6 .__crossx-pw-fields {
2341
- gap: 16px;
2342
- }
2343
- .__crossx-card--pin6 .__crossx-pw-fields--notice {
2344
- flex: 1;
2345
- min-height: 0;
2346
- overflow-y: auto;
2347
- -webkit-overflow-scrolling: touch;
2348
- }
2349
- .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 16px; }
2350
- .__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
2351
- .__crossx-card--pin6 .__crossx-pin6-body {
2352
- flex: 1;
2353
- min-height: 0;
2354
- overflow-y: auto;
2355
- padding: 16px;
2356
- gap: 16px;
2357
- }
2358
- .__crossx-card--pin6 .__crossx-pin6-next { flex-shrink: 0; }
2359
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) {
2360
- display: grid;
2361
- grid-template-columns: 1fr 1fr;
2362
- grid-template-rows: auto auto 1fr;
2363
- }
2364
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-header,
2365
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) > .__crossx-divider {
2366
- grid-column: 1 / -1;
2367
- }
2368
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-body {
2369
- grid-column: 1;
2370
- grid-row: 3;
2371
- justify-content: center;
2372
- align-items: center;
2373
- overflow: hidden;
2374
- }
2375
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-numpad {
2376
- grid-column: 2;
2377
- grid-row: 3;
2378
- display: flex !important;
2379
- padding: 16px 10px;
2380
- gap: 4px;
2381
- overflow: hidden;
2382
- }
2383
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-box,
2384
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-dot {
2385
- width: 36px;
2386
- height: 36px;
2387
- font-size: 16px;
2388
- }
2389
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-numpad-row {
2390
- gap: 4px;
2391
- }
2392
- .__crossx-card--pin6:has(.__crossx-pin6-numpad):not(.--native-keypad) .__crossx-pin6-numpad-key {
2393
- height: 43.5px;
2394
- max-width: none;
2395
- border-radius: 4px;
2396
- font-size: 18px;
2397
- }
2398
- }
2399
-
2400
- /* ── 6-digit wallet PIN box input ──────────────────────────────────── */
2401
- .__crossx-card--pin6 {
2402
- width: 100%;
2403
- max-width: 540px;
2404
- }
2405
- .__crossx-pin6-sheet-handle {
2406
- display: none;
2407
- }
2408
- /* PIN6 Notice 화면 body/fields: Figma 기준 px-24 */
2409
- .__crossx-card--pin6 .__crossx-pw-body {
2410
- padding: 24px;
2411
- gap: 32px;
2412
- }
2413
- .__crossx-card--pin6 .__crossx-pw-fields {
2414
- gap: 32px;
2415
- }
2416
- .__crossx-pin6-footer {
2417
- display: flex;
2418
- flex-direction: column;
2419
- align-items: center;
2420
- justify-content: center;
2421
- width: 100%;
2422
- padding: 12px 24px 24px;
2423
- background: var(--cx-bg);
2424
- box-sizing: border-box;
2425
- }
2426
- .__crossx-card--pin6 .__crossx-pw-btn.--disabled {
2427
- opacity: 0.5;
2428
- cursor: pointer;
2429
- }
2430
- .__crossx-pin6-header-sub {
2431
- font-size: 14px;
2432
- font-weight: 400;
2433
- color: var(--cx-subtitle);
2434
- line-height: 1.5;
2435
- margin: 0;
2436
- letter-spacing: -0.01em;
2437
- }
2438
- .__crossx-pin6-body {
2439
- display: flex;
2440
- flex-direction: column;
2441
- align-items: center;
2442
- padding: 40px 24px 72px;
2443
- gap: 16px;
2444
- width: 100%;
2445
- box-sizing: border-box;
2446
- }
2447
- .__crossx-pin6-subtitle {
2448
- font-size: 14px;
2449
- font-weight: 400;
2450
- color: var(--cx-subtitle);
2451
- text-align: center;
2452
- margin: 0;
2453
- line-height: 1.5;
2454
- letter-spacing: -0.01em;
2455
- width: 100%;
2456
- }
2457
- .__crossx-pin6-boxes {
2458
- display: flex;
2459
- gap: 8px;
2460
- align-items: center;
2461
- justify-content: center;
2462
- padding: 0;
2463
- }
2464
- .__crossx-pin6-box {
2465
- width: clamp(36px, 12vw, 48px);
2466
- height: clamp(36px, 12vw, 48px);
2467
- border-radius: 12px;
2468
- border: none;
2469
- background: var(--cx-input-bg);
2470
- font-size: 20px;
2471
- font-weight: 600;
2472
- text-align: center;
2473
- color: var(--cx-value);
2474
- outline: none;
2475
- caret-color: transparent;
2476
- letter-spacing: 0;
2477
- -webkit-tap-highlight-color: transparent;
2478
- transition: background 0.12s, box-shadow 0.12s;
2479
- }
2480
- .__crossx-pin6-box:focus {
2481
- background: var(--cx-input-border);
2482
- box-shadow: 0 0 0 2px var(--cx-primary-glow);
2483
- }
2484
- .__crossx-pin6-box.--error {
2485
- /* 에러 시 박스 자체에는 별도 스타일 없음 — 에러 텍스트로만 표시 */
2486
- }
2487
- .__crossx-pin6-box.--locked,
2488
- .__crossx-pin6-box:disabled {
2489
- opacity: 0.4;
2490
- pointer-events: none;
2491
- }
2492
- .__crossx-pin6-boxes.--shake {
2493
- animation: __crossx-pin6-shake 0.4s ease;
2494
- }
2495
- @keyframes __crossx-pin6-shake {
2496
- 0%, 100% { transform: translateX(0); }
2497
- 20% { transform: translateX(-8px); }
2498
- 40% { transform: translateX(8px); }
2499
- 60% { transform: translateX(-6px); }
2500
- 80% { transform: translateX(6px); }
2501
- }
2502
- .__crossx-pin6-error {
2503
- font-size: 14px;
2504
- font-weight: 400;
2505
- color: var(--cx-error);
2506
- text-align: center;
2507
- margin: 0;
2508
- line-height: 1.5;
2509
- width: 100%;
2510
- letter-spacing: -0.01em;
2511
- }
2512
- .__crossx-pin6-error:empty,
2513
- .__crossx-pin6-warning:empty,
2514
- .__crossx-pin6-attempt:empty {
2515
- display: none;
2516
- }
2517
- /* 잠금 메시지 + 카운트다운 */
2518
- .__crossx-pin6-lock-msg {
2519
- display: flex;
2520
- align-items: center;
2521
- gap: 6px;
2522
- font-size: 13px;
2523
- font-weight: 500;
2524
- color: var(--cx-error);
2525
- text-align: center;
2526
- margin: 0;
2527
- }
2528
- .__crossx-pin6-lock-msg svg {
2529
- flex-shrink: 0;
2530
- color: var(--cx-error);
2531
- }
2532
- /* 시도 횟수 카운트 (X/Y) */
2533
- .__crossx-pin6-attempt {
2534
- font-size: 16px;
2535
- font-weight: 500;
2536
- line-height: 1.5;
2537
- color: var(--cx-error);
2538
- text-align: center;
2539
- letter-spacing: -0.16px;
2540
- margin: 0;
2541
- }
2542
- .__crossx-pin6-warning {
2543
- font-size: 14px;
2544
- font-weight: 500;
2545
- line-height: 1.5;
2546
- color: var(--cx-error);
2547
- text-align: center;
2548
- margin: 0;
2549
- }
2550
- /* Next 버튼 */
2551
- .__crossx-pin6-next {
2552
- width: 100%;
2553
- background: var(--cx-primary-gradient);
2554
- color: var(--cx-on-primary);
2555
- border: none;
2556
- border-radius: 12px;
2557
- cursor: pointer;
2558
- transition: opacity 0.15s;
2559
- -webkit-tap-highlight-color: transparent;
2560
- height: 48px;
2561
- }
2562
- .__crossx-pin6-next:disabled,
2563
- .__crossx-pin6-next.--disabled {
2564
- opacity: 0.5;
2565
- cursor: default;
2566
- }
2567
-
2568
- /* ─── PIN6 virtual numpad (mobile action sheet) ────────────────── */
2569
- .__crossx-pin6-dots {
2570
- display: none;
2571
- gap: 8px;
2572
- align-items: center;
2573
- justify-content: center;
2574
- padding: 0; /* Figma: 안내문과 간격 16 (body gap) */
2575
- }
2576
- .__crossx-pin6-dot {
2577
- width: clamp(36px, 12vw, 48px);
2578
- height: clamp(36px, 12vw, 48px);
2579
- border-radius: 12px;
2580
- background: var(--cx-input-bg);
2581
- display: flex;
2582
- align-items: center;
2583
- justify-content: center;
2584
- font-size: 20px;
2585
- font-weight: 600;
2586
- color: var(--cx-value);
2587
- flex-shrink: 0;
2588
- transition: background 0.12s;
2589
- }
2590
- .__crossx-pin6-dot.--filled::after {
2591
- content: '';
2592
- display: block;
2593
- width: 12px;
2594
- height: 12px;
2595
- border-radius: 50%;
2596
- background: var(--cx-value);
2597
- }
2598
- .__crossx-pin6-dot.--active {
2599
- background: var(--cx-input-border);
2600
- box-shadow: 0 0 0 2px var(--cx-primary-glow);
2601
- }
2602
- .__crossx-pin6-dot.--locked {
2603
- opacity: 0.4;
2604
- pointer-events: none;
2605
- }
2606
- .__crossx-pin6-numpad {
2607
- display: none;
2608
- flex-direction: column;
2609
- gap: 7px;
2610
- padding: 6px;
2611
- width: 100%;
2612
- background: var(--cx-bg);
2613
- flex-shrink: 0;
2614
- }
2615
- .__crossx-pin6-numpad-row {
2616
- display: flex;
2617
- gap: 6px;
2618
- justify-content: center;
2619
- }
2620
- .__crossx-pin6-numpad-key {
2621
- flex: 1;
2622
- max-width: 130px;
2623
- height: 46px;
2624
- border-radius: 5px;
2625
- border: none;
2626
- background: var(--cx-surface-subtle);
2627
- box-shadow: 0 1px 0 0 var(--cx-divider);
2628
- font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Segoe UI', sans-serif;
2629
- font-size: 25px;
2630
- font-weight: 400;
2631
- color: var(--cx-value);
2632
- cursor: pointer;
2633
- display: flex;
2634
- align-items: center;
2635
- justify-content: center;
2636
- user-select: none;
2637
- -webkit-user-select: none;
2638
- -webkit-tap-highlight-color: transparent;
2639
- outline: none;
2640
- touch-action: manipulation;
2641
- transition: background 0.08s;
2642
- }
2643
- .__crossx-pin6-numpad-key:hover,
2644
- .__crossx-pin6-numpad-key:focus,
2645
- .__crossx-pin6-numpad-key:active {
2646
- outline: none !important;
2647
- box-shadow: 0 1px 0 0 var(--cx-divider) !important;
2648
- filter: none !important;
2649
- }
2650
- .__crossx-pin6-numpad-key:active:not(.--disabled),
2651
- .__crossx-pin6-numpad-key.--pressed:not(.--disabled) {
2652
- background: var(--cx-input-border);
2653
- }
2654
- .__crossx-pin6-numpad-key.--empty {
2655
- background: transparent;
2656
- box-shadow: none;
2657
- pointer-events: none;
2658
- }
2659
- .__crossx-pin6-numpad-key.--delete {
2660
- background: transparent;
2661
- box-shadow: none;
2662
- color: var(--cx-value);
2663
- pointer-events: auto;
2664
- }
2665
- .__crossx-pin6-numpad-key.--delete:active {
2666
- opacity: 0.5;
2667
- }
2668
- .__crossx-pin6-numpad-key.--disabled {
2669
- opacity: 0.3;
2670
- pointer-events: none;
2671
- }
2672
-
2673
- /* ─── Session alert modal ──────────────────────────────────────── */
2674
- .__crossx-session-hero {
2675
- display: flex;
2676
- flex-direction: column;
2677
- gap: 8px;
2678
- align-items: center;
2679
- width: 100%;
2680
- }
2681
- /* 헤더 제목과 같은 문구가 본문에 한 번 더 나온다 — Figma 4045:14458 에는 없어 숨긴다(마크업 유지) */
2682
- .__crossx-session-hero-title {
2683
- display: none;
2684
- }
2685
- .__crossx-session-hero-message {
2686
- font-size: 16px;
2687
- font-weight: 400;
2688
- line-height: 1.5;
2689
- color: var(--cx-subtitle);
2690
- text-align: center;
2691
- margin: 0;
2692
- white-space: pre-line;
2693
- }
2694
- .__crossx-session-account-card {
2695
- background: var(--cx-pill-bg);
2696
- border-radius: 12px;
2697
- padding: 16px;
2698
- display: flex;
2699
- flex-direction: column;
2700
- gap: 8px;
2701
- align-items: center;
2702
- width: 100%;
2703
- box-sizing: border-box;
2704
- }
2705
- .__crossx-session-account-label {
2706
- font-size: 14px;
2707
- font-weight: 600;
2708
- line-height: 1.5;
2709
- color: var(--cx-close);
2710
- margin: 0;
2711
- }
2712
- .__crossx-session-account-email {
2713
- font-size: 18px;
2714
- font-weight: 600;
2715
- line-height: 1.5;
2716
- color: var(--cx-content-high);
2717
- word-break: break-all;
2718
- margin: 0;
2719
- }
2720
-
2721
- /* ── Wallet Created Modal ───────────────────────────────────── */
2722
- .__crossx-card--wallet-created {
2723
- width: 540px;
2724
- max-width: calc(100vw - 32px);
2725
- display: flex;
2726
- flex-direction: column;
2727
- }
2728
- /* Figma: 제목만 있는 헤더 — 제목 아래 4px 여백 없음 (헤더 높이 73) */
2729
- .__crossx-card--wallet-created .__crossx-title {
2730
- margin-bottom: 0;
2731
- }
2732
- .__crossx-wallet-created-sheet-handle {
2733
- display: none;
2734
- }
2735
- .__crossx-wallet-created-body {
2736
- padding: 24px;
2737
- width: 100%;
2738
- box-sizing: border-box;
2739
- }
2740
- .__crossx-wallet-created-hero {
2741
- height: 285px;
2742
- display: flex;
2743
- align-items: center;
2744
- justify-content: center;
2745
- width: 100%;
2746
- }
2747
- ${vc}
2748
- .__crossx-wallet-created-footer {
2749
- padding: 12px 24px 24px;
2750
- width: 100%;
2751
- box-sizing: border-box;
2752
- }
2753
- .__crossx-wallet-created-btn {
2754
- width: 100%;
2755
- border: none;
2756
- border-radius: 12px;
2757
- background: var(--cx-primary-gradient);
2758
- color: var(--cx-on-primary);
2759
- font-family: inherit;
2760
- letter-spacing: -0.01em;
2761
- cursor: pointer;
2762
- }
2763
- .__crossx-wallet-created-btn:hover,
2764
- .__crossx-wallet-created-btn:focus,
2765
- .__crossx-wallet-created-btn:active {
2766
- opacity: 1 !important;
2767
- box-shadow: none !important;
2768
- outline: none !important;
2769
- filter: none !important;
2770
- transform: none !important;
2771
- background: var(--cx-primary-gradient) !important;
2772
- color: var(--cx-on-primary) !important;
2773
- }
2774
-
2775
- /* ── Amount tooltip ──────────────────────────────────────────────── */
2776
- .__crossx-amount-tip {
2777
- cursor: default;
2778
- }
2779
- .__crossx-tip-overlay {
2780
- position: fixed;
2781
- background: #111827;
2782
- color: #e2e8f0;
2783
- border-radius: 8px;
2784
- padding: 6px 10px;
2785
- font-size: 12px;
2786
- font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
2787
- line-height: 1.4;
2788
- white-space: nowrap;
2789
- pointer-events: none;
2790
- z-index: 1;
2791
- box-shadow: 0 4px 12px rgba(0,0,0,0.3);
2792
- display: none;
2793
- }
2794
- .__crossx-tip-overlay.--visible {
2795
- display: block;
2796
- }
2797
- `;function le(){let s=document.getElementById(vn);s||(s=document.createElement("style"),s.id=vn,document.head.appendChild(s)),s.textContent=Ac}function Tc(){const s=`#${Y}`,e=t=>{var n,i;(i=(n=t.target)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()},r=t=>{var n,i;(i=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&i.call(n,s)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",r,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",r,!0)}}function de(s){const e=s.querySelector(".__crossx-card");if(e){const a=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(a){const c=a[1].trim();s.style.setProperty("--cx-bg",c);const l=document.createElement("div");l.className="__crossx-safe-area-fill",l.style.background=c,s.appendChild(l)}}const r=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(o,r);s.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])s.addEventListener(o,r);s.addEventListener("touchmove",o=>{o.stopPropagation();let a=o.target;for(;a&&a!==s;){const c=window.getComputedStyle(a);if((c.overflowY==="auto"||c.overflowY==="scroll")&&a.scrollHeight>a.clientHeight)return;a=a.parentElement}o.preventDefault()},{passive:!1});const t=Tc(),n=Rc(s),i=s.remove.bind(s);s.remove=()=>{n(),t(),i()},document.body.appendChild(s)}function Rc(s){if(typeof window>"u")return()=>{};const e=window.visualViewport;if(!e)return()=>{};let r=-1;const t=()=>{const n=window.innerHeight,i=e.offsetTop+e.height,o=Math.max(0,Math.round(n-i));o!==r&&(r=o,s.style.setProperty("--cx-keyboard-inset",`${o}px`))};return t(),e.addEventListener("resize",t),e.addEventListener("scroll",t),()=>{e.removeEventListener("resize",t),e.removeEventListener("scroll",t),s.style.removeProperty("--cx-keyboard-inset")}}function Nc(s){const e=Array.from(s.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",s.appendChild(r);let t=null;const n=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const c=o.getBoundingClientRect(),l=r.offsetWidth,d=r.offsetHeight;let p=c.right-l,f=c.top-d-6;p<8&&(p=8),f<8&&(f=c.bottom+6),r.style.left=`${p}px`,r.style.top=`${f}px`,t=o},i=()=>{r.classList.remove("--visible"),t=null};e.forEach(o=>{o.addEventListener("mouseenter",()=>n(o)),o.addEventListener("mouseleave",i),o.addEventListener("touchstart",a=>{a.stopPropagation(),t===o?i():n(o)},{passive:!0})}),s.addEventListener("touchstart",o=>{o.target.closest(".__crossx-amount-tip")||i()},{passive:!0})}const Cc=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Le(){if(Cc()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function Ae(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function In(s){return s?s.length<=13?s:`${s.slice(0,6)}...${s.slice(-4)}`:"—"}function An(s,e="ONE",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=Ar(n,r,t);if(i==="0")return null;const o=Er(n,r);return Ir(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const Tn={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"ONEchain Testnet",612055:"CROSS Mainnet"},br=new Map;let Sr=!1;function Oc(){if(Sr||(Sr=!0,typeof fetch>"u"))return;const s=wt().contentsBaseUrl;s&&fetch(`${s}/chains.json`,{cache:"no-store"}).then(e=>e.ok?e.json():null).then(e=>{const r=e==null?void 0:e.chains;if(r)for(const[t,n]of Object.entries(r)){const i=Number(t);!Number.isNaN(i)&&n&&br.set(i,n)}}).catch(()=>{Sr=!1})}function Rn(s){return parseInt(s.split(":")[1]??"",10)}function Nn(s){var r;const e=Rn(s);if(!isNaN(e)){const t=(r=br.get(e))==null?void 0:r.name;if(t)return t;if(Tn[e])return Tn[e]}return s}function vr(s,e){var r;if(s){const t=Rn(s);if(!isNaN(t)){const n=(r=br.get(t))==null?void 0:r.nativeSymbol;if(n)return n}}return e}function Er(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,i=(s%r).toString().padStart(e,"0").replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function Ir(s,e){return s===e?v(s):`<span class="__crossx-amount-tip" data-full="${v(e)}">${v(s)}</span>`}function Ar(s,e,r){if(s===0n)return"0";const t=10n**BigInt(e),n=s/t,a=(s%t).toString().padStart(e,"0").slice(0,r).replace(/0+$/,"");return a?`${n}.${a}`:`${n}`}function Tr(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function kc(s){try{return BigInt(s).toLocaleString()}catch{return s}}function Pc(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeDecimals:o=18}=s,a=vr(s.chainId,s.nativeSymbol??"ETH");if(!r)return null;try{const c=BigInt(r),l=kc(r);if(n){const d=c*BigInt(n);return{isDynamic:!0,estTxFee:Ir(`${Ar(d,o,e)} ${a}`,`${Er(d,o)} ${a}`),maxFeeGwei:Tr(n),maxPriorityFeeGwei:i?Tr(i):void 0,gasLimitFormatted:l}}if(t){const d=c*BigInt(t);return{isDynamic:!1,estTxFee:Ir(`${Ar(d,o,e)} ${a}`,`${Er(d,o)} ${a}`),gasPriceGwei:Tr(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function Cn(s,e,r){const t=Pc(s,e);if(!t)return te((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=te((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=te((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=te((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=te((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=te((r==null?void 0:r.label_gas_limit)??"Gas Limit",`<span>${t.gasLimitFormatted}</span>`)),n}const Te=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2798
- <rect x="9" y="9" width="13" height="13" rx="2"/>
2799
- <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
2800
- </svg>`,ie='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6L18 18"/></svg>',Dc='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 318.6 318.6" aria-hidden="true"><style>.st1,.st6{fill:#e4761b;stroke:#e4761b;stroke-linecap:round;stroke-linejoin:round}.st6{fill:#f6851b;stroke:#f6851b}</style><path fill="#e2761b" stroke="#e2761b" stroke-linecap="round" stroke-linejoin="round" d="m274.1 35.5-99.5 73.9L193 65.8z"/><path d="m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z" class="st1"/><path d="m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z" class="st1"/><path fill="#d7c1b3" stroke="#d7c1b3" stroke-linecap="round" stroke-linejoin="round" d="m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"/><path fill="#233447" stroke="#233447" stroke-linecap="round" stroke-linejoin="round" d="m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"/><path fill="#cd6116" stroke="#cd6116" stroke-linecap="round" stroke-linejoin="round" d="m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"/><path fill="#e4751f" stroke="#e4751f" stroke-linecap="round" stroke-linejoin="round" d="m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"/><path d="m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z" class="st6"/><path fill="#c0ad9e" stroke="#c0ad9e" stroke-linecap="round" stroke-linejoin="round" d="m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"/><path fill="#161616" stroke="#161616" stroke-linecap="round" stroke-linejoin="round" d="m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"/><path fill="#763d16" stroke="#763d16" stroke-linecap="round" stroke-linejoin="round" d="m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"/><path d="m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z" class="st6"/></svg>',Lc='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 126.611 126.611" aria-hidden="true"><polygon fill="#F3BA2F" points="38.171,53.203 62.759,28.616 87.36,53.216 101.667,38.909 62.759,0 23.864,38.896 "/><rect x="3.644" y="53.188" transform="matrix(0.7071 0.7071 -0.7071 0.7071 48.7933 8.8106)" fill="#F3BA2F" width="20.233" height="20.234"/><polygon fill="#F3BA2F" points="38.171,73.408 62.759,97.995 87.359,73.396 101.674,87.695 101.667,87.703 62.759,126.611 23.863,87.716 23.843,87.696 "/><rect x="101.64" y="53.189" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 235.5457 29.0503)" fill="#F3BA2F" width="20.234" height="20.233"/><polygon fill="#F3BA2F" points="77.271,63.298 77.277,63.298 62.759,48.78 52.03,59.509 52.029,59.509 50.797,60.742 48.254,63.285 48.254,63.285 48.234,63.305 48.254,63.326 62.759,77.831 77.277,63.313 77.284,63.305 "/></svg>';function On(s,e){return`<svg width="${s}" height="${s}" viewBox="0 0 229 229" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><g clip-path="url(#clip0_${e})"><rect width="228.273" height="228.273" rx="87" fill="white"/><path d="M228.307 -0.0644531H0.0332031V228.209H228.307V-0.0644531Z" fill="#CE3E35"/><path d="M33.9219 43.7533C33.9219 31.934 43.5033 22.3527 55.3225 22.3527H173.019C184.838 22.3527 194.419 31.9341 194.419 43.7533V123.107H33.9219V43.7533Z" fill="white"/><g filter="url(#filter0_d_${e})"><path d="M228.241 228.21H0.0332031V56.5961C0.0332031 48.7166 6.4208 42.329 14.3003 42.329H77.9502C84.6851 42.329 90.1926 47.3831 94.2527 52.7566C98.8699 58.8676 106.06 62.7958 114.137 62.7958C122.214 62.7958 129.404 58.8676 134.021 52.7566C138.081 47.3831 143.589 42.329 150.324 42.329H213.974C221.854 42.329 228.241 48.7166 228.241 56.5961V228.21Z" fill="url(#paint0_linear_${e})"/></g><path d="M79.7598 228.096H228.24V64.7367L79.7598 159.851V228.096Z" fill="url(#paint1_linear_${e})"/><path d="M79.7694 228.209H0.0332031V75.9257L79.7694 160.218V228.209Z" fill="url(#paint2_linear_${e})"/><g filter="url(#filter1_d_${e})"><path d="M113.105 89.2908L81.3322 107.655C75.7279 110.878 73.7862 118.118 77.0076 123.724C80.229 129.331 87.4661 131.273 93.0704 128.051L119.945 112.511L107.147 126.241V180.098C107.147 186.588 112.443 191.885 118.93 191.885C125.417 191.885 130.712 186.588 130.712 180.098V99.4884C130.712 97.237 130.006 95.0297 129.124 93.5729C125.814 88.0106 118.665 86.024 113.061 89.2466L113.105 89.2908Z" fill="white"/></g></g><defs><filter id="filter0_d_${e}" x="-7.10034" y="33.4121" width="242.474" height="200.148" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dy="-1.78339"/><feGaussianBlur stdDeviation="3.56677"/><feComposite in2="hardAlpha" operator="out"/><feColorMatrix type="matrix" values="0 0 0 0 0.892803 0 0 0 0 0.220099 0 0 0 0 0.293135 0 0 0 0.5 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_${e}"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_${e}" result="shape"/></filter><filter id="filter1_d_${e}" x="67.9009" y="80.1489" width="75.3839" height="124.308" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/><feOffset dx="2.51084" dy="2.51084"/><feGaussianBlur stdDeviation="5.03056"/><feColorMatrix type="matrix" values="0 0 0 0 0.831373 0 0 0 0 0.113725 0 0 0 0 0.356863 0 0 0 0.3 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_${e}"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_${e}" result="shape"/></filter><linearGradient id="paint0_linear_${e}" x1="-26.3993" y1="19.4879" x2="193.409" y2="286.17" gradientUnits="userSpaceOnUse"><stop stop-color="#F3752D"/><stop offset="1" stop-color="#EC1272"/></linearGradient><linearGradient id="paint1_linear_${e}" x1="56.978" y1="73.7355" x2="168.096" y2="169.248" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><linearGradient id="paint2_linear_${e}" x1="142.362" y1="29.5078" x2="37.3384" y2="166.255" gradientUnits="userSpaceOnUse"><stop stop-color="white" stop-opacity="0.5"/><stop offset="1" stop-color="white" stop-opacity="0"/></linearGradient><clipPath id="clip0_${e}"><rect width="228.273" height="228.273" rx="87" fill="white"/></clipPath></defs></svg>`}const Bc=On(16,"connect-inline"),Mc={[We.MetaMask]:Dc,[We.Binance]:Lc,[We.CROSSx]:Bc},$c='<path d="M22.6667 11.8333V10.1667C22.6667 9.2475 21.9192 8.5 21.0001 8.5H10.1667C8.78841 8.5 7.66675 9.62167 7.66675 11V21C7.66675 22.8342 9.16175 23.5 10.1667 23.5H22.6667C23.5859 23.5 24.3334 22.7525 24.3334 21.8333V13.5C24.3334 12.5808 23.5859 11.8333 22.6667 11.8333ZM21.0001 19.3333H19.3334V16H21.0001V19.3333ZM10.1667 11.8333C9.95218 11.8237 9.74959 11.7317 9.60114 11.5765C9.4527 11.4213 9.36986 11.2148 9.36986 11C9.36986 10.7852 9.4527 10.5787 9.60114 10.4235C9.74959 10.2683 9.95218 10.1763 10.1667 10.1667H21.0001V11.8333H10.1667Z"/>',Rr='<svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><path d="M17.4076 5.37036V3.51851C17.4076 2.49722 16.5771 1.66666 15.5558 1.66666H3.51874C1.98726 1.66666 0.740967 2.91296 0.740967 4.44444V15.5555C0.740967 17.5935 2.40208 18.3333 3.51874 18.3333H17.4076C18.4289 18.3333 19.2595 17.5028 19.2595 16.4815V7.22222C19.2595 6.20092 18.4289 5.37036 17.4076 5.37036ZM15.5558 13.7037H13.7039V9.99999H15.5558V13.7037ZM3.51874 5.37036C3.28034 5.3597 3.05523 5.25749 2.8903 5.08501C2.72536 4.91253 2.63331 4.68308 2.63331 4.44444C2.63331 4.20579 2.72536 3.97634 2.8903 3.80387C3.05523 3.63139 3.28034 3.52918 3.51874 3.51851H15.5558V5.37036H3.51874Z"/></svg>',Uc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2801
- <path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="var(--cx-error)"/>
2802
- </svg>`,Fc=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2803
- <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
2804
- <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
2805
- <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
2806
- </svg>`;function ce(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-border-medium:${s.borderMedium}`,`--cx-title:${s.titleColor}`,`--cx-content-high:${s.contentHigh}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-surface-high:${s.surfaceHigh}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-primary-gradient:${s.primaryGradient}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-notice-bg:${s.noticeBg}`,`--cx-notice-border:${s.noticeBorder}`,`--cx-notice-title:${s.noticeTitleColor}`,`--cx-on-primary:${s.onPrimary}`,`--cx-wc-sparkle:${s.sparkleColor}`,`--cx-warning:${s.warningColor}`].join(";")}function Wc(s,e){s.style.setProperty("--cx-bg",e.bg),s.style.setProperty("--cx-border",e.border),s.style.setProperty("--cx-border-medium",e.borderMedium),s.style.setProperty("--cx-title",e.titleColor),s.style.setProperty("--cx-subtitle",e.subtitleColor),s.style.setProperty("--cx-label",e.labelColor),s.style.setProperty("--cx-value",e.valueColor),s.style.setProperty("--cx-pill-bg",e.pillBg),s.style.setProperty("--cx-pill-from",e.pillFromColor),s.style.setProperty("--cx-pill-amt",e.pillAmtColor),s.style.setProperty("--cx-divider",e.divider),s.style.setProperty("--cx-close",e.closeColor),s.style.setProperty("--cx-close-hover",e.closeHoverBg),s.style.setProperty("--cx-copy",e.copyColor),s.style.setProperty("--cx-input-bg",e.inputBg),s.style.setProperty("--cx-input-border",e.inputBorder),s.style.setProperty("--cx-hint",e.hintColor),s.style.setProperty("--cx-surface-subtle",e.surfaceSubtle),s.style.setProperty("--cx-surface-high",e.surfaceHigh),s.style.setProperty("--cx-primary",e.primary),s.style.setProperty("--cx-primary-glow",e.primaryGlow),s.style.setProperty("--cx-primary-gradient",e.primaryGradient),s.style.setProperty("--cx-secondary",e.secondary),s.style.setProperty("--cx-error",e.errorColor),s.style.setProperty("--cx-notice-bg",e.noticeBg),s.style.setProperty("--cx-notice-border",e.noticeBorder),s.style.setProperty("--cx-notice-title",e.noticeTitleColor),s.style.setProperty("--cx-on-primary",e.onPrimary),s.style.setProperty("--cx-wc-sparkle",e.sparkleColor),s.style.setProperty("--cx-warning",e.warningColor)}function te(s,e){return`
2807
- <div class="__crossx-row">
2808
- <span class="__crossx-row-label">${s}</span>
2809
- <div class="__crossx-row-value">${e}</div>
2810
- </div>`}function Hc(s,e,r,t){const n=e,i=vr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=Dt(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ae(s.to)}</span>
2811
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=Cn(s,r,t),d=An(s.value,i,o,r),p=d?te((t==null?void 0:t.label_value)??"Value",`<span>${d}</span>`):"",f=s.data??"0x",g=/^(0x)?$/i.test(f.trim())?"":`<pre class="__crossx-raw-tx">${v(f)}</pre>`,w=document.createElement("div");return w.id=Y,w.innerHTML=`
2812
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ce(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2813
- <div class="__crossx-header">
2814
- <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
2815
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2816
- </div>
2817
- <hr class="__crossx-divider">
2818
- <div class="__crossx-body">
2819
- <div class="__crossx-body-cols">
2820
- <div class="__crossx-col-left">
2821
- <p class="__crossx-sig-subtitle">
2822
- <span class="__crossx-sig-origin">${v(a)}</span>${v((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
2823
- </p>
2824
- <div class="__crossx-addr-pill">
2825
- ${Rr}
2826
- <span class="__crossx-addr-pill-text">${Ae(s.from)}</span>
2827
- </div>
2828
- <p class="__crossx-warning">${v((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2829
- </div>
2830
- <hr class="__crossx-divider __crossx-divider--cols">
2831
- <div class="__crossx-col-right-sign">
2832
- <div class="__crossx-rows">
2833
- ${te((t==null?void 0:t.label_to)??"To",c)}
2834
- ${te((t==null?void 0:t.label_network)??"Network",`<span>${Nn(s.chainId)}</span>`)}
2835
- ${p}
2836
- ${l}
2837
- </div>
2838
- ${g}
2839
- </div>
2840
- </div>
2841
- <div class="__crossx-btn-row">
2842
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${v((t==null?void 0:t.cancel)??"Cancel")}</button>
2843
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${v((t==null?void 0:t.signature_sign_button)??"Sign")}</button>
2844
- </div>
2845
- </div>
2846
- </div>
2847
- `,w}const Gc=new Set(["0x095ea7b3","0xa22cb465","0xd505accf","0x8fcbaf0c"]);function Kc(s){return s?Gc.has(s.slice(0,10).toLowerCase()):!1}function Vc(s,e,r,t){const n=e,i=vr(s.chainId,s.nativeSymbol??"ETH"),o=s.nativeDecimals??18,a=Dt(s.dappName),c=s.to?`<span class="__crossx-addr-text">${Ae(s.to)}</span>
2848
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=Cn(s,r,t),p=An(s.value,i,o,r)??"—",f=Kc(s.data)?(t==null?void 0:t.send_tx_approve_button)??"Approve":(t==null?void 0:t.send_tx_confirm_button)??"Confirm",g=document.createElement("div");return g.id=Y,g.innerHTML=`
2849
- <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ce(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2850
- <div class="__crossx-header">
2851
- <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
2852
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2853
- </div>
2854
- <hr class="__crossx-divider">
2855
- <div class="__crossx-body">
2856
- <p class="__crossx-tx-subtitle">
2857
- <span class="__crossx-sig-origin">${v(a)}</span>${v((t==null?void 0:t.send_tx_permission_text)??" wants your permission to approve the following transaction.")}
2858
- </p>
2859
- <div class="__crossx-body-cols">
2860
- <div class="__crossx-rows">
2861
- ${te((t==null?void 0:t.label_to)??"To",c)}
2862
- ${te((t==null?void 0:t.label_network)??"Network",`<span>${Nn(s.chainId)}</span>`)}
2863
- ${l}
2864
- </div>
2865
- <div class="__crossx-pill">
2866
- <span class="__crossx-pill-from">${Ae(s.from)}</span>
2867
- <span class="__crossx-pill-amount">${p}</span>
2868
- </div>
2869
- </div>
2870
- <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${v(f)}</button>
2871
- </div>
2872
- </div>
2873
- `,g}function Dt(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function v(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function qc(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function zc(s){if(typeof s=="string")return v(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return v(JSON.stringify(s))}catch{return String(s)}}function Jc(s){return s.includes(":")?s.split(":")[1]??s:s}function jc(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function Yc(s,e){return`https://explorer.crosstoken.io/${Jc(s)}/tx/${e}`}function kn(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${v(e)}" target="_blank" rel="noopener noreferrer">${v(s)}</a>`}function Lt(s){return kn(Ae(s),jc(s))}function Pn(s,e){return kn(Ae(e),Yc(s,e))}function Xc(s,e,r){const t=te((r==null?void 0:r.label_from)??"From",`${Lt(s.from)}
2874
- <button class="__crossx-copy-btn" data-copy="${v(s.from)}" title="Copy address">${Te}</button>`),n=s.to?te((r==null?void 0:r.label_to)??"To",`${Lt(s.to)}
2875
- <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`):"",i=s.amount?te((r==null?void 0:r.label_transfer)??"Transfer",`<span>${v(s.amount)}</span>`):"",o=s.fees?te((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${v(s.fees)}</span>`):"",a=s.txHash?te((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${Pn(s.chainId,s.txHash)}
2876
- <button class="__crossx-copy-btn" data-copy="${v(s.txHash)}" title="Copy hash">${Te}</button>`):"",c=s.total?`<div class="__crossx-total-pill">
2877
- <span class="__crossx-total-label">${v((r==null?void 0:r.label_total)??"Total")}<br>${v((r==null?void 0:r.label_including_fees)??"(including fees)")}</span>
2878
- <span class="__crossx-total-amount">${v(s.total)}</span>
2879
- </div>`:"",l=document.createElement("div");return l.id=Y,l.innerHTML=`
2880
- <div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2881
- <div class="__crossx-header">
2882
- <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
2883
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2884
- </div>
2885
- <hr class="__crossx-divider">
2886
- <div class="__crossx-body">
2887
- <div class="__crossx-rows">
2888
- ${t}
2889
- ${n}
2890
- ${i}
2891
- ${o}
2892
- ${a}
2893
- </div>
2894
- ${c}
2895
- <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
2896
- </div>
2897
- </div>
2898
- `,l}function Zc(s,e,r){const t=document.createElement("div");return t.id=Y,t.innerHTML=`
2899
- <div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2900
- <div class="__crossx-header">
2901
- <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
2902
- </div>
2903
- <hr class="__crossx-divider">
2904
- <div class="__crossx-body" id="__crossx-progress-body">
2905
- <div class="__crossx-progress-center">
2906
- <div class="__crossx-spinner"></div>
2907
- <p class="__crossx-progress-text">${v((r==null?void 0:r.tx_progress_waiting_text)??"Waiting for transaction receipt...")}</p>
2908
- </div>
2909
- </div>
2910
- </div>
2911
- `,t}function Qc(s,e,r,t){const n=e.status!=="reverted"&&e.status!=="timeout",i=e.status==="timeout",o=s.querySelector("#__crossx-ttl"),a=s.querySelector(".__crossx-header");if(o){const m=i?Fc:n?"":Uc,x=i?(t==null?void 0:t.tx_timeout)??"Transaction timeout":n?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";m?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${m}<span>${v(x)}</span>`):o.textContent=x}if(a&&!s.querySelector("#__crossx-close-btn")){const m=document.createElement("button");m.className="__crossx-close",m.id="__crossx-close-btn",m.setAttribute("aria-label","Close"),m.innerHTML=ie,a.appendChild(m)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?te((t==null?void 0:t.label_from)??"From",`${Lt(e.from)}
2912
- <button class="__crossx-copy-btn" data-copy="${v(e.from)}" title="Copy address">${Te}</button>`):"",d=e.to?te((t==null?void 0:t.label_to)??"To",`${Lt(e.to)}
2913
- <button class="__crossx-copy-btn" data-copy="${v(e.to)}" title="Copy address">${Te}</button>`):"",p=e.amount?te((t==null?void 0:t.label_transfer)??"Transfer",`<span>${v(e.amount)}</span>`):"",f=e.fees?te((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${v(e.fees)}</span>`):"",g=e.txHash?te((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${Pn(e.chainId,e.txHash)}
2914
- <button class="__crossx-copy-btn" data-copy="${v(e.txHash)}" title="Copy hash">${Te}</button>`):"",w=e.total?`<div class="__crossx-total-pill">
2915
- <span class="__crossx-total-label">${v((t==null?void 0:t.label_total)??"Total")}<br>${v((t==null?void 0:t.label_including_fees)??"(including fees)")}</span>
2916
- <span class="__crossx-total-amount">${v(e.total)}</span>
2917
- </div>`:"";c.innerHTML=`
2918
- <div class="__crossx-rows">
2919
- ${l}
2920
- ${d}
2921
- ${p}
2922
- ${f}
2923
- ${g}
2924
- </div>
2925
- ${w}
2926
- <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((t==null?void 0:t.tx_complete_done_button)??(n?"All Done":"Done"))}</button>
2927
- `,c.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",x=>{var I;x.stopPropagation();const S=m.dataset.copy;S&&((I=navigator.clipboard)==null||I.writeText(S).catch(()=>{}))})})}function el(s,e,r){const t=e,n=Dt(s.dappName),i=v(s.message),o=document.createElement("div");return o.id=Y,o.innerHTML=`
2928
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2929
- <div class="__crossx-header">
2930
- <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
2931
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2932
- </div>
2933
- <hr class="__crossx-divider">
2934
- <div class="__crossx-body">
2935
- <div class="__crossx-body-cols">
2936
- <div class="__crossx-col-left">
2937
- <p class="__crossx-sig-subtitle">
2938
- <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2939
- </p>
2940
- <div class="__crossx-addr-pill">
2941
- ${Rr}
2942
- <span class="__crossx-addr-pill-text">${Ae(s.from)}</span>
2943
- </div>
2944
- <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2945
- </div>
2946
- <hr class="__crossx-divider __crossx-divider--cols">
2947
- <div class="__crossx-msg-raw">${i}</div>
2948
- </div>
2949
- <div class="__crossx-btn-row">
2950
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${v((r==null?void 0:r.cancel)??"Cancel")}</button>
2951
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${v((r==null?void 0:r.confirm)??"Confirm")}</button>
2952
- </div>
2953
- </div>
2954
- </div>
2955
- `,o}function tl(s,e,r){const t=e,n=Dt(s.dappName);let i={};if(typeof s.typedData=="string")try{i=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(i=s.typedData);const o=i.primaryType??"—",a=i.message??{};let c=`
2956
- <div class="__crossx-td-row">
2957
- <span class="__crossx-td-label">${v((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
2958
- <span class="__crossx-td-value">${v(o)}</span>
2959
- </div>`;for(const[d,p]of Object.entries(a)){const f=zc(p),w=qc(p)?`<span class="__crossx-addr-text">${Ae(p)}</span>
2960
- <button class="__crossx-copy-btn" data-copy="${v(String(p))}" title="Copy">${Te}</button>`:`<span>${f}</span>`;c+=`
2961
- <div class="__crossx-td-row">
2962
- <span class="__crossx-td-label">${v(d)}</span>
2963
- <div class="__crossx-td-value">${w}</div>
2964
- </div>`}const l=document.createElement("div");return l.id=Y,l.innerHTML=`
2965
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2966
- <div class="__crossx-header">
2967
- <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
2968
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
2969
- </div>
2970
- <hr class="__crossx-divider">
2971
- <div class="__crossx-body">
2972
- <div class="__crossx-body-cols">
2973
- <div class="__crossx-col-left">
2974
- <p class="__crossx-sig-subtitle">
2975
- <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2976
- </p>
2977
- <div class="__crossx-addr-pill">
2978
- ${Rr}
2979
- <span class="__crossx-addr-pill-text">${Ae(s.from)}</span>
2980
- </div>
2981
- <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2982
- </div>
2983
- <hr class="__crossx-divider __crossx-divider--cols">
2984
- <div class="__crossx-td-rows">${c}</div>
2985
- </div>
2986
- <div class="__crossx-btn-row">
2987
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${v((r==null?void 0:r.cancel)??"Cancel")}</button>
2988
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${v((r==null?void 0:r.confirm)??"Confirm")}</button>
2989
- </div>
2990
- </div>
2991
- </div>
2992
- `,l}const rl='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12H19M12 5V19"/></svg>',sl='<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="var(--cx-primary, #00ceb2)"/><path d="M7.5 12.5L10.5 15.5L16.5 8.5" stroke="var(--cx-on-primary, #000)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Dn(s){return s.name||`Account ${s.index+1}`}function nl(){return`<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><rect width="32" height="32" rx="16" fill="#121212" fill-opacity="0.1"/><g fill="#121212" fill-opacity="0.5">${$c}</g></svg>`}const il=wt().portraitBaseUrl;function ol(s,e){const r=e.replace("#","");return`${il}/portrait/evm/${encodeURIComponent(s)}.png?size=256&bg=${encodeURIComponent(r)}`}function Ln(s,e,r){const t=ol(s,r),i=nl().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${v(t)}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function al(s,e,r,t,n=!0){const i=s.length===0,o=n||i?`<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2993
- <span class="__crossx-wallet-add-icon">${rl}</span>
2994
- <span class="__crossx-wallet-add-label">${v((t==null?void 0:t.wallet_selector_add_button)??"Add Wallet")}</span>
2995
- </button>
2996
- <p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>`:"",a=r==null?void 0:r.toLowerCase(),c=s.map(p=>{const f=a&&p.address.toLowerCase()===a,g=f?" __crossx-wallet-item--selected":"",w=f?`<span class="__crossx-wallet-selected">${v((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${sl}</span>`:"";return`<button class="__crossx-wallet-item${g}" data-wallet-index="${v(String(p.index))}" data-wallet-address="${v(p.address)}">
2997
- ${Ln(p.address,p.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(Dn(p))}</span><span class="__crossx-wallet-addr">${v(In(p.address))}</span></span>${w}
2998
- </button>`}).join(""),l=i?`<p class="__crossx-wallet-empty" id="__crossx-wallet-empty">${v((t==null?void 0:t.wallet_selector_empty)??"No wallet yet. Add a wallet to continue.")}</p>`:"",d=document.createElement("div");return d.id=Y,d.className="__crossx-overlay--wallet-selector",d.innerHTML=`
2999
- <div class="__crossx-card __crossx-card--wallet-selector" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3000
- <div class="__crossx-header">
3001
- <span class="__crossx-wallet-sheet-handle" aria-hidden="true"></span>
3002
- <div class="__crossx-wallet-header-copy">
3003
- <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
3004
- <p class="__crossx-subtitle--body">${v((t==null?void 0:t.wallet_selector_description)??"Please select the wallet you previously used for this game to continue.")}</p>
3005
- </div>
3006
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3007
- </div>
3008
- <hr class="__crossx-divider">
3009
- <div class="__crossx-body __crossx-wallet-selector-body">
3010
- <div class="__crossx-wallet-list-section">
3011
- <div class="__crossx-wallet-list" id="__crossx-wallet-list">
3012
- ${c}${l}
3013
- </div>
3014
- ${o}
3015
- </div>
3016
- <div class="__crossx-wallet-help-section">
3017
- <div class="__crossx-mig-info">
3018
- <p class="__crossx-mig-info-title">${v((t==null?void 0:t.wallet_selector_info_title)??"Why do I need to select a wallet?")}</p>
3019
- <p class="__crossx-mig-info-desc">${v((t==null?void 0:t.wallet_selector_info_desc)??"Identifying your previously linked wallet ensures your game progress and assets are synced correctly.")}</p>
3020
- </div>
3021
- </div>
3022
- </div>
3023
- </div>
3024
- `,d}function cl(s,e){const r=document.createElement("div");r.id=Y;const t=document.createElement("div");t.className="__crossx-card __crossx-card--wallet-created",Wc(t,s),t.role="dialog",t.ariaModal="true",t.setAttribute("aria-labelledby","__crossx-ttl");const n=document.createElement("div");n.className="__crossx-header";const i=document.createElement("span");i.className="__crossx-wallet-created-sheet-handle",i.ariaHidden="true";const o=document.createElement("p");o.className="__crossx-title",o.id="__crossx-ttl",o.style.paddingRight="48px",o.textContent=(e==null?void 0:e.wallet_created_title)??"Wallet Created!";const a=document.createElement("button");a.className="__crossx-close",a.id="__crossx-close-btn",a.type="button",a.ariaLabel="Close",a.innerHTML=ie,n.append(i,o,a);const c=document.createElement("hr");c.className="__crossx-divider";const l=document.createElement("div");l.className="__crossx-wallet-created-body";const d=document.createElement("div");d.className="__crossx-wallet-created-hero";const p=document.createElement("span");p.className="__crossx-wallet-created-illust",p.ariaHidden="true",p.innerHTML=Sc,d.appendChild(p),l.appendChild(d);const f=document.createElement("div");f.className="__crossx-wallet-created-footer";const g=document.createElement("button");return g.className="__crossx-wallet-created-btn",g.id="__crossx-wallet-created-done",g.type="button",g.textContent=(e==null?void 0:e.wallet_created_button)??"Got it",f.appendChild(g),t.append(n,c,l,f),r.appendChild(t),r}const ll=`<svg width="32" height="32" viewBox="4.62 5.5 30.16 30.16" fill="none" xmlns="http://www.w3.org/2000/svg">
3025
- <path d="M26.693 21.193c-.028-3.168 2.587-4.712 2.706-4.786-1.477-2.16-3.77-2.454-4.58-2.484-1.944-.197-3.804 1.148-4.793 1.148-.992 0-2.52-1.12-4.147-1.09-2.13.032-4.1 1.239-5.198 3.133-2.222 3.855-.569 9.562 1.593 12.69 1.061 1.535 2.318 3.258 3.975 3.196 1.6-.064 2.2-1.03 4.133-1.03 1.928 0 2.48 1.03 4.172.997 1.72-.03 2.806-1.56 3.862-3.1 1.211-1.779 1.713-3.495 1.74-3.583-.037-.017-3.427-1.316-3.463-5.09z" fill="currentColor"/>
3026
- <path d="M23.527 11.876c.877-1.065 1.471-2.545 1.31-4.024-1.266.053-2.807.845-3.718 1.907-.813.946-1.53 2.468-1.34 3.915 1.41.107 2.852-.716 3.748-1.798z" fill="currentColor"/>
3027
- </svg>`,dl=`<svg width="32" height="32" viewBox="-2.77 -2.77 45.54 45.54" fill="none" xmlns="http://www.w3.org/2000/svg">
3028
- <path d="M38.06 20.44c0-1.34-.12-2.63-.34-3.87H20.5v7.32h9.84c-.42 2.28-1.71 4.21-3.65 5.51v4.57h5.91c3.46-3.19 5.46-7.88 5.46-13.53z" fill="#4285F4"/>
3029
- <path d="M20.5 38.5c4.94 0 9.09-1.64 12.12-4.44l-5.91-4.57c-1.64 1.1-3.73 1.75-6.21 1.75-4.77 0-8.82-3.22-10.26-7.55H4.16v4.72A18.49 18.49 0 0 0 20.5 38.5z" fill="#34A853"/>
3030
- <path d="M10.24 23.69A11.16 11.16 0 0 1 9.66 20c0-1.28.22-2.52.58-3.69v-4.72H4.16A18.49 18.49 0 0 0 2 20c0 2.97.71 5.78 1.97 8.28l6.27-4.59z" fill="#FBBC05"/>
3031
- <path d="M20.5 8.76c2.69 0 5.1.92 7 2.73l5.24-5.24C29.58 3.36 25.43 1.5 20.5 1.5A18.49 18.49 0 0 0 4.16 11.59l6.08 4.72C11.68 11.98 15.73 8.76 20.5 8.76z" fill="#EA4335"/>
3032
- </svg>`;function ul(s){const e=$r(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Mc[s]??""}</span><span class="__crossx-connect-other-wallet-name">${v(e)}</span></span>`}function hl(s){if(s.length===0)return"";const e=n=>ul(s[n]),r="Supported wallets include ";if(s.length===1)return`${r}${e(0)}.`;if(s.length===2)return`${r}${e(0)} and ${e(1)}.`;if(s.length===3)return`${r}${e(0)}, ${e(1)} and ${e(2)}.`;const t=s.length-3;return`${r}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function pl(s,e=[],r){const t=s,n=v(String(e[0])),i=v((r==null?void 0:r.login_selector_or)??"or"),o=e.length>0?`
3033
- <div class="__crossx-login-or-divider">
3034
- <hr><span>${i}</span><hr>
3035
- </div>
3036
- <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${n}" aria-labelledby="__crossx-connect-other-heading">
3037
- <span class="__crossx-connect-other-text">
3038
- <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">${v((r==null?void 0:r.login_selector_connect_other_wallets)??"Connect with Other Wallets")}</span>
3039
- <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${hl(e)}</span>
3040
- </span>
3041
- </button>`:"",a=document.createElement("div");return a.id=Y,a.innerHTML=`
3042
- <div class="__crossx-card __crossx-card--migration __crossx-card--login" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3043
- <div class="__crossx-header">
3044
- <span class="__crossx-login-sheet-handle" aria-hidden="true"></span>
3045
- <div class="__crossx-login-title-wrap" style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
3046
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${v((r==null?void 0:r.login_selector_title)??pt)}</p>
3047
- <p class="__crossx-subtitle">${v((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
3048
- </div>
3049
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3050
- </div>
3051
- <hr class="__crossx-divider">
3052
- <div class="__crossx-body">
3053
- <div class="__crossx-login-btn-row">
3054
- <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
3055
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${ll}</span>
3056
- <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
3057
- </button>
3058
- <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
3059
- <span class="__crossx-login-icon">${dl}</span>
3060
- <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
3061
- </button>
3062
- </div>${o}
3063
- <p class="__crossx-login-terms">
3064
- ${((r==null?void 0:r.login_selector_terms_template)??"By continuing, you agree to NEXUS {tos} and consent to its {pp}").replace("{tos}",`<a class="__crossx-login-terms-link" href="https://terms.onechain.nexus/docs/terms-july-23-2026" target="_blank" rel="noopener noreferrer">${v((r==null?void 0:r.login_selector_terms_tos)??"Terms of Service")}</a>`).replace("{pp}",`<a class="__crossx-login-terms-link" href="https://terms.onechain.nexus/docs/pp-july-23-2026" target="_blank" rel="noopener noreferrer">${v((r==null?void 0:r.login_selector_terms_pp)??"Privacy Policy.")}</a>`)}
3065
- </p>
3066
- </div>
3067
- </div>
3068
- `,a}function _l(s,e){const r=s,t=document.createElement("div");t.id=Y;const n=v(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
3069
- <p class="__crossx-session-account-label">${v(e.accountLabel)}</p>
3070
- <p class="__crossx-session-account-email">${v(e.email)}</p>
3071
- </div>`:"";return t.innerHTML=`
3072
- <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
3073
- <div class="__crossx-header">
3074
- <p class="__crossx-title" id="__crossx-session-header-title">${v(e.title)}</p>
3075
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3076
- </div>
3077
- <hr class="__crossx-divider">
3078
- <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
3079
- <div class="__crossx-session-hero">
3080
- <p class="__crossx-session-hero-title">${v(e.title)}</p>
3081
- <p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
3082
- </div>
3083
- ${i}
3084
- <div class="__crossx-btn-row">
3085
- <button class="__crossx-cancel-btn" id="__crossx-session-signout">${v(e.signOutLabel)}</button>
3086
- <button class="__crossx-confirm-btn" id="__crossx-session-signin">${v(e.signInAgainLabel)}</button>
3087
- </div>
3088
- </div>
3089
- </div>
3090
- `,t}function fl(s,e){const r=document.createElement("div");r.id=Y;const t=v(e.message).replace(/\n/g,"<br>");return r.innerHTML=`
3091
- <div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-update-title" aria-describedby="__crossx-update-msg">
3092
- <div class="__crossx-header">
3093
- <p class="__crossx-title" id="__crossx-update-title">${v(e.title)}</p>
3094
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3095
- </div>
3096
- <hr class="__crossx-divider">
3097
- <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
3098
- <div class="__crossx-session-hero">
3099
- <p class="__crossx-session-hero-message" id="__crossx-update-msg">${t}</p>
3100
- </div>
3101
- <div class="__crossx-btn-row">
3102
- <button class="__crossx-confirm-btn" id="__crossx-update-ok">${v(e.confirmLabel)}</button>
3103
- </div>
3104
- </div>
3105
- </div>
3106
- `,r}function gl(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=Y,i.innerHTML=`
3107
- <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3108
- <div class="__crossx-header">
3109
- <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
3110
- <p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
3111
- ${t}
3112
- </div>
3113
- <hr class="__crossx-divider">
3114
- <div class="__crossx-body">
3115
- <div class="__crossx-mig-info">
3116
- <p class="__crossx-mig-info-title">What is a Recovery Wallet?</p>
3117
- <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
3118
- </div>
3119
- <button class="__crossx-recover-btn" id="__crossx-recover-btn">
3120
- <span class="__crossx-recover-icon">${On(40,"recover")}</span>
3121
- <span class="__crossx-recover-label">Import from Social Backup</span>
3122
- </button>
3123
- ${n}
3124
- </div>
3125
- </div>
3126
- `,i}function xl(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=Y,p.innerHTML=`
3127
- <div class="__crossx-card __crossx-card--migration" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3128
- <div class="__crossx-header">
3129
- <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
3130
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3131
- </div>
3132
- <hr class="__crossx-divider">
3133
- <div class="__crossx-pin-center">
3134
- ${c}
3135
- ${l}
3136
- <div class="__crossx-pin-inputs">
3137
- <input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
3138
- <input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
3139
- <input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
3140
- <input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
3141
- </div>
3142
- <p class="__crossx-pin-hint">Enter your 4-digit PIN to recover your wallet.</p>
3143
- ${d}
3144
- </div>
3145
- </div>
3146
- `,p}function wl(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function ml(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?wl(i):null,a=document.createElement("div");return a.id=Y,a.innerHTML=`
3147
- <div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3148
- <div class="__crossx-header">
3149
- <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
3150
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3151
- </div>
3152
- <hr class="__crossx-divider">
3153
- <div class="__crossx-pin-center">
3154
- <div class="__crossx-pin-inputs">
3155
- <div class="__crossx-pin-dot" aria-hidden="true">●</div>
3156
- <div class="__crossx-pin-dot" aria-hidden="true">●</div>
3157
- <div class="__crossx-pin-dot" aria-hidden="true">●</div>
3158
- <div class="__crossx-pin-dot" aria-hidden="true">●</div>
3159
- </div>
3160
- <div class="__crossx-pin-lock-messages">
3161
- <p class="__crossx-pin-lock-message">${n?r:"Please try again after the lock expires."}</p>
3162
- ${o?`<p class="__crossx-pin-lock-secondary">(Available from ${o})</p>`:""}
3163
- </div>
3164
- </div>
3165
- </div>
3166
- `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function yl(s){const r=[s.check1,s.check2].map((t,n)=>`
3167
- <div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
3168
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${El}</div>
3169
- <span class="__crossx-pw-notice-item-text">${v(t)}</span>
3170
- </div>
3171
- `).join("");return`
3172
- <div class="__crossx-header">
3173
- <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
3174
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
3175
- <p class="__crossx-pw-subtitle">${v(s.headerSubtitle)}</p>
3176
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3177
- </div>
3178
- <hr class="__crossx-divider">
3179
- <div class="__crossx-pw-body">
3180
- <div class="__crossx-pw-fields __crossx-pw-fields--notice">
3181
- <div class="__crossx-pw-notice-header">
3182
- <div class="__crossx-pw-notice-title-row">
3183
- <span class="__crossx-pw-notice-icon">${Il}</span>
3184
- <p class="__crossx-pw-notice-title">${v(s.noticeTitle)}</p>
3185
- </div>
3186
- <p class="__crossx-pw-notice-desc">${v(s.noticeDesc)}</p>
3187
- </div>
3188
- <div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
3189
- ${r}
3190
- </div>
3191
- </div>
3192
- </div>
3193
- <div class="__crossx-pin6-footer">
3194
- <button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
3195
- data-next-label="${v(s.nextButton)}"
3196
- data-submit-label="${v(s.submitButton)}">
3197
- ${v(s.submitButton)}
3198
- </button>
3199
- </div>
3200
- <div class="__crossx-home-indicator"></div>
3201
- `}function Nr(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${v(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${v(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${v(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
3202
- ${Mn}
3203
- <span id="__crossx-pin6-lock-countdown"></span>
3204
- </p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${v(s.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",d=Array.from({length:6},(m,x)=>`<input class="__crossx-pin6-box${l}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" aria-label="PIN digit ${x+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",f=Array.from({length:6},(m,x)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${x}" aria-label="PIN digit ${x+1}"></div>`).join(""),g=e?" --disabled":"",w=`
3205
- <div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
3206
- <div class="__crossx-pin6-numpad-row">
3207
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="1">1</button>
3208
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="2">2</button>
3209
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="3">3</button>
3210
- </div>
3211
- <div class="__crossx-pin6-numpad-row">
3212
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="4">4</button>
3213
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="5">5</button>
3214
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="6">6</button>
3215
- </div>
3216
- <div class="__crossx-pin6-numpad-row">
3217
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="7">7</button>
3218
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="8">8</button>
3219
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="9">9</button>
3220
- </div>
3221
- <div class="__crossx-pin6-numpad-row">
3222
- <button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
3223
- <button type="button" class="__crossx-pin6-numpad-key${g}" data-key="0">0</button>
3224
- <button type="button" class="__crossx-pin6-numpad-key --delete${g}" data-key="backspace" aria-label="Delete">${vl}</button>
3225
- </div>
3226
- </div>`;return`
3227
- <div class="__crossx-header">
3228
- <span class="__crossx-pin6-sheet-handle" aria-hidden="true"></span>
3229
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
3230
- ${t}
3231
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
3232
- </div>
3233
- <hr class="__crossx-divider">
3234
- <div class="__crossx-pin6-body"${r}>
3235
- ${n}
3236
- <div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
3237
- ${d}
3238
- <div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
3239
- ${f}
3240
- </div>
3241
- </div>
3242
- ${i}
3243
- ${a}
3244
- ${c}
3245
- ${o}
3246
- </div>
3247
- ${w}
3248
- `}function Bn(s,e){const r=document.createElement("div");return r.id=Y,r.innerHTML=`
3249
- <div class="__crossx-card __crossx-card--pin6" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
3250
- ${e}
3251
- </div>
3252
- `,r}function bl(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function Sl(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function Cr(s,e,r,t,n,i,o){var k,V;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),d=()=>s.querySelector("#__crossx-pin6-boxes"),p=()=>s.querySelector("#__crossx-pin6-error"),f=()=>s.querySelector("#__crossx-pin6-lock-msg"),g=()=>s.querySelector("#__crossx-pin6-lock-countdown"),w=()=>s.querySelector(".__crossx-pin6-body"),m="●",x=(E,A)=>{E.dataset.digit=A,E.value=m},S=E=>{delete E.dataset.digit,E.value=""},I=E=>E.dataset.digit??"",U=()=>l().map(I).join(""),C=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),L=()=>{var N;const E=l(),A=C();if(A.length&&(A.forEach((T,K)=>{const J=!!(E[K]&&I(E[K]));T.classList.toggle("--filled",J),T.classList.toggle("--active",!1)}),!a&&!c)){const T=E.findIndex(J=>!I(J));(N=A[T===-1?5:T])==null||N.classList.add("--active")}},H=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(A=>A.classList.toggle("--disabled",a)),C().forEach(A=>A.classList.toggle("--locked",a)),L()},G=E=>{a=E,l().forEach(A=>{A.disabled=E,A.classList.toggle("--locked",E)})},q=()=>s.querySelector("#__crossx-pin6-attempt"),z=()=>{const E=p();E&&(E.textContent="")},ne=()=>o??"Your account will be locked after further failures.",D=()=>s.querySelector("#__crossx-pin6-warning"),F=E=>{var N;let A=D();if(!A){A=document.createElement("p"),A.className="__crossx-pin6-warning",A.id="__crossx-pin6-warning";const T=p();T?T.insertAdjacentElement("afterend",A):(N=w())==null||N.appendChild(A)}A.textContent=E},W=()=>{const E=D();E&&(E.textContent="")},y=(E,A)=>{var T;let N=q();if(!N){N=document.createElement("p"),N.className="__crossx-pin6-attempt",N.id="__crossx-pin6-attempt";const K=D()??p();K?K.insertAdjacentElement("afterend",N):(T=w())==null||T.appendChild(N)}N.textContent=`${E}/${A}`},b=()=>{const E=q();E&&(E.textContent="")},R=E=>{const A=p();A&&(A.textContent=E);const N=d();N==null||N.classList.add("--shake"),setTimeout(()=>N==null?void 0:N.classList.remove("--shake"),500),l().forEach(S),setTimeout(()=>{var T;(T=l()[0])==null||T.focus(),L()},50)},O=E=>{var J;G(!0),l().forEach(S),H();const A=p();if(A&&(A.textContent="Too many failed attempts. Please wait."),!f()){const Z=document.createElement("p");Z.className="__crossx-pin6-lock-msg",Z.id="__crossx-pin6-lock-msg",Z.innerHTML=`${Mn}<span id="__crossx-pin6-lock-countdown"></span>`;const j=p();j?j.insertAdjacentElement("afterend",Z):(J=w())==null||J.appendChild(Z)}const N=()=>{var Q;const Z=E-Date.now(),j=g();Z<=0?(clearInterval(T),G(!1),(Q=f())==null||Q.remove(),A&&(A.textContent=""),H(),setTimeout(()=>{var Fe;return(Fe=l()[0])==null?void 0:Fe.focus()},50)):j&&(j.textContent=` ${Sl(Z)}`)},T=setInterval(N,1e3);N();const K=new MutationObserver(()=>{document.contains(s)||(clearInterval(T),K.disconnect())});K.observe(document.body,{childList:!0,subtree:!1})},$=async()=>{if(a||c)return;const E=U();if(E.length===6){c=!0,l().forEach(A=>{A.disabled=!0});try{if(n){const A=await n(E);A.ok?e(E):A.lockExpiresAt?(b(),O(A.lockExpiresAt)):(R(A.error??"Incorrect PIN. Please try again."),A.attemptCount!=null&&A.maxAttempts!=null?(F(ne()),y(A.attemptCount,A.maxAttempts)):(W(),b()))}else e(E)}catch(A){t&&t(A)}finally{c=!1,a||l().forEach(A=>{A.disabled=!1}),L()}}};i&&i>Date.now()?O(i):setTimeout(()=>{var E;return(E=l()[0])==null?void 0:E.focus()},100);const B=()=>{if(a||c)return;const E=l(),A=E.find(N=>!I(N))??E[E.length-1];A==null||A.focus()};(k=d())==null||k.addEventListener("click",E=>{E.target.classList.contains("__crossx-pin6-box")||B()}),(V=w())==null||V.addEventListener("click",E=>{const A=E.target;A.classList.contains("__crossx-pin6-box")||A.closest("button")||B()}),l().forEach((E,A)=>{E.addEventListener("input",()=>{var T;const N=E.value.replace(/\D/g,"").slice(-1);N?x(E,N):S(E),z(),N&&A<5&&((T=l()[A+1])==null||T.focus()),L(),U().length===6&&setTimeout($,80)}),E.addEventListener("keydown",N=>{var T,K;if(N.key==="Backspace"){if(N.preventDefault(),I(E))S(E);else if(A>0){const J=l()[A-1];S(J),J.focus()}L()}else N.key==="ArrowLeft"&&A>0?(N.preventDefault(),(T=l()[A-1])==null||T.focus()):N.key==="ArrowRight"&&A<5?(N.preventDefault(),(K=l()[A+1])==null||K.focus()):N.key==="Escape"&&r()}),E.addEventListener("paste",N=>{var J,Z;N.preventDefault();const T=(((J=N.clipboardData)==null?void 0:J.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!T)return;const K=l();T.split("").forEach((j,Q)=>{K[Q]&&x(K[Q],j)}),(Z=K[Math.min(T.length-1,5)])==null||Z.focus(),z(),L(),U().length===6&&setTimeout($,80)}),E.addEventListener("focus",()=>E.select())});const M=s.querySelector("#__crossx-pin6-numpad");if(M){let E=null;const A=()=>{E&&(E.classList.remove("--pressed"),E=null)};M.addEventListener("pointerdown",T=>{const K=T.target.closest(".__crossx-pin6-numpad-key");!K||a||c||(A(),E=K,K.classList.add("--pressed"),K.setPointerCapture(T.pointerId))});const N=T=>{const K=T.dataset.key;if(!K)return;if(K==="backspace"){const Q=[...l()].reverse().find(Fe=>I(Fe));Q&&(S(Q),z()),L();return}if(!/^\d$/.test(K))return;const Z=l().find(j=>!I(j));Z&&(x(Z,K),z(),L(),U().length===6&&setTimeout($,80))};M.addEventListener("pointerup",T=>{if(!E)return;const K=E;A();const J=K.getBoundingClientRect();T.clientX>=J.left&&T.clientX<=J.right&&T.clientY>=J.top&&T.clientY<=J.bottom&&!a&&!c&&N(K)}),M.addEventListener("pointercancel",A),M.addEventListener("pointerleave",A,!0),L(),i&&i>Date.now()&&H()}}const vl=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
3253
- <path d="M7.36 0.5H19.5C20.6046 0.5 21.5 1.39543 21.5 2.5V14.5C21.5 15.6046 20.6046 16.5 19.5 16.5H7.36C6.76 16.5 6.19 16.24 5.8 15.79L0.94 10.02C0.35 9.32 0.35 8.3 0.94 7.6L5.8 1.71C6.19 1.26 6.76 0.5 7.36 0.5Z" stroke="currentColor" stroke-width="1.2" fill="none"/>
3254
- <line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3255
- <line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
3256
- </svg>`,Mn=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
3257
- <path d="M14.5 8.5H14V6.5C14 4.015 11.985 2 9.5 2C7.015 2 5 4.015 5 6.5V8.5H4.5C3.672 8.5 3 9.172 3 10V16.5C3 17.328 3.672 18 4.5 18H14.5C15.328 18 16 17.328 16 16.5V10C16 9.172 15.328 8.5 14.5 8.5ZM10.5 13.415V15C10.5 15.276 10.276 15.5 10 15.5H9C8.724 15.5 8.5 15.276 8.5 15V13.415C8.187 13.196 8 12.847 8 12.5C8 11.672 8.672 11 9.5 11C10.328 11 11 11.672 11 12.5C11 12.847 10.813 13.196 10.5 13.415ZM12.5 8.5H6.5V6.5C6.5 4.843 7.843 3.5 9.5 3.5C11.157 3.5 12.5 4.843 12.5 6.5V8.5Z" fill="currentColor"/>
3258
- </svg>`,El=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
3259
- <path d="M1 4.5L4 7.5L10 1" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
3260
- </svg>`,Il=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3261
- <circle cx="12" cy="12" r="10" fill="currentColor"/>
3262
- <path d="M11.0625 13.3564H12.9375V7.51895H11.0625V13.3564ZM11.0625 16.4814H12.9375V14.6064H11.0625V16.4814Z" fill="#FFFFFF"/>
3263
- </svg>`;function Al(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(d=>d.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((f,g)=>{t[g]&&(t[g].value=f)});const d=Math.min(l.length,3);t[d].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Tl{constructor(e="light",r,t=$t,n){this.theme=e,this.overrides=r,this.tokens=En(e,r),this.displayDecimals=t,this.pinKeyboard=n,Oc()}setPinKeyboard(e){this.pinKeyboard=e}resolvePinKeyboardMode(){const e=this.pinKeyboard;if(typeof e=="function")try{return e()==="native"?"native":"virtual"}catch{return"virtual"}return e==="native"?"native":"virtual"}applyPinKeyboardMode(e){e&&e.classList.toggle("--native-keypad",this.resolvePinKeyboardMode()==="native")}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=En(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t,n){return new Promise((i,o)=>{var U;le();const a=[...e],c=al(a,this.tokens,t,this.messages,(n==null?void 0:n.showAddWallet)!==!1),l=Le();de(c);let d=!1;const p=()=>{d||(d=!0,c.remove(),l())};let f=null;const g=C=>{p(),i(C)},w=()=>{p(),f?o(f):i(null)};(()=>{c.querySelectorAll(".__crossx-wallet-item").forEach(C=>{C.addEventListener("click",()=>{const L=C.dataset.walletAddress??"",H=parseInt(C.dataset.walletIndex??"0",10),G=a.find(q=>q.index===H);g({address:L,index:H,name:G==null?void 0:G.name})})})})();const x=c.querySelector("#__crossx-add-wallet-error"),S=c.querySelector("#__crossx-add-wallet-btn");S&&S.addEventListener("click",async()=>{var C;S.disabled=!0,x&&(x.hidden=!0,x.textContent="");try{const L=await r();a.push(L),(C=c.querySelector("#__crossx-wallet-empty"))==null||C.remove();const H=c.querySelector("#__crossx-wallet-list");if(H){const G=document.createElement("button");G.className="__crossx-wallet-item",G.dataset.walletIndex=String(L.index),G.dataset.walletAddress=L.address,G.innerHTML=`${Ln(L.address,L.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(Dn(L))}</span><span class="__crossx-wallet-addr">${v(In(L.address))}</span></span>`,G.addEventListener("click",()=>g(L)),H.appendChild(G);try{G.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}if((n==null?void 0:n.showAddWallet)===!1){S.remove(),x==null||x.remove();return}S.disabled=!1}catch(L){const H=L instanceof _&&L.code===h.ADDRESS_LIMIT_EXCEEDED,G=this.resolveAddWalletErrorMessage(L);x&&(x.textContent=G,x.hidden=!1),H?(S.disabled=!0,S.setAttribute("aria-disabled","true")):S.disabled=!1,f=L}}),(U=c.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",w),c.addEventListener("click",C=>{C.target===c&&w()});const I=C=>{C.key==="Escape"&&(document.removeEventListener("keydown",I),w())};document.addEventListener("keydown",I)})}showWalletCreatedPrompt(){return new Promise(e=>{var a,c;le();const r=cl(this.tokens,this.messages),t=Le();de(r);let n=!1,i=null;const o=()=>{n||(n=!0,i&&document.removeEventListener("keydown",i),r.remove(),t(),e())};(a=r.querySelector("#__crossx-wallet-created-done"))==null||a.addEventListener("click",o),(c=r.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),r.addEventListener("click",l=>{l.target===r&&o()}),i=l=>{l.key==="Escape"&&o()},document.addEventListener("keydown",i)})}resolveAddWalletErrorMessage(e){const r=this.messages;if(e instanceof _&&e.code===h.ADDRESS_LIMIT_EXCEEDED){const n=e.details,i=typeof(n==null?void 0:n.limit)=="number"?n.limit:dt;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var f,g,w,m;le();const i=pl(this.tokens,r,this.messages),o=Le();de(i);const a=()=>{i.remove(),o()},c=x=>{a(),n({type:"oauth",provider:x})},l=x=>{a(),n({type:"external",walletId:x})},d=()=>{a(),n(null)};(f=i.querySelector("#__crossx-apple-btn"))==null||f.addEventListener("click",()=>c("apple")),(g=i.querySelector("#__crossx-google-btn"))==null||g.addEventListener("click",()=>c("google")),(w=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||w.addEventListener("click",x=>{const I=x.currentTarget.dataset.walletId??"";I&&l(I)}),(m=i.querySelector("#__crossx-close-btn"))==null||m.addEventListener("click",d),i.addEventListener("click",x=>{x.target===i&&d()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(x=>{x.addEventListener("click",S=>S.stopPropagation())});const p=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)})}showUpdateRequired(e){return new Promise(r=>{var l,d;le();const t=this.messages,n=fl(this.tokens,{title:(e==null?void 0:e.title)??(t==null?void 0:t.update_required_title)??"Update required",message:(e==null?void 0:e.message)??(t==null?void 0:t.update_required_message)??"This service is using a wallet version that is no longer supported. Please try again after the service is updated.",confirmLabel:(t==null?void 0:t.update_required_confirm_button)??"OK"}),i=Le();de(n);let o=!1;const a=()=>{o||(o=!0,document.removeEventListener("keydown",c),n.remove(),i(),r())},c=p=>{p.key==="Escape"&&a()};document.addEventListener("keydown",c),(l=n.querySelector("#__crossx-update-ok"))==null||l.addEventListener("click",a),(d=n.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",a)})}showSessionAlert(e){return new Promise(r=>{var d,p,f;le();const t=this.messages,n=_l(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.session_alert_account_label)??"Account",signOutLabel:(t==null?void 0:t.session_alert_sign_out_button)??"Sign out",signInAgainLabel:(t==null?void 0:t.session_alert_sign_in_again_button)??"Sign in again"}),i=Le();de(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(d=n.querySelector("#__crossx-session-signout"))==null||d.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;le();const n=gl(this.tokens,r);de(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const d=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",d),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",d),n.addEventListener("click",f=>{f.target===n&&d()});const p=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",p),d())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(r=>{le();const t=this.messages,n={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pin_notice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},i={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pin_setup_mismatch_error)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Confirm your 6-digit PIN"},a=Bn(this.tokens,yl(n)),c=Le();de(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())},p=I=>{d(),r(I)},f=()=>{d(),r(null)},g=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},m=I=>{var U;g.innerHTML=Nr({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle}),this.applyPinKeyboardMode(g),(U=g.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",f),Cr(g,C=>{C===I?p(I):x(i.mismatchError)},f)},x=I=>{var U;g.innerHTML=Nr({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:I}),this.applyPinKeyboardMode(g),(U=g.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",f),Cr(g,C=>{const L=bl(C,w);L?x(L):m(C)},f)};(()=>{var ne;const I=Array.from(g.querySelectorAll(".__crossx-pw-notice-item")),U=g.querySelector("#__crossx-pin-notice-next"),C=new Set;U.removeAttribute("disabled");const L=U.dataset.nextLabel??"Next",H=U.dataset.submitLabel??"I Understand",G=()=>{const D=C.size===I.length;U.classList.toggle("--disabled",!D),U.textContent=H||L},q=(D,F)=>{if(C.has(F))return;const W=D.querySelector(`#__crossx-notice-check-${F}`);C.add(F),W.classList.add("--checked"),D.setAttribute("aria-checked","true"),G()},z=(D,F)=>{if(!C.has(F))return;const W=D.querySelector(`#__crossx-notice-check-${F}`);C.delete(F),W.classList.remove("--checked"),D.setAttribute("aria-checked","false"),G()};I.forEach(D=>{const F=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{C.has(F)?z(D,F):q(D,F)}),D.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),C.has(F)?z(D,F):q(D,F))})}),U.addEventListener("click",()=>{if(C.size===I.length){x(e==null?void 0:e.errorMessage);return}const D=I.find(W=>{const y=parseInt(W.dataset.checkIndex??"0",10);return!C.has(y)});if(!D)return;const F=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),q(D,F)},400)}),(ne=g.querySelector("#__crossx-close-btn"))==null||ne.addEventListener("click",f)})(),a.addEventListener("click",I=>{I.target===a&&f()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var S;le();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verify_pin_title)??"Verify Your PIN":(n==null?void 0:n.pin_input_title)??"Enter PIN",a=i?(n==null?void 0:n.verify_pin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pin_input_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pin_locked_failure_warning)??"Your account will be locked after further failures.",l=Bn(this.tokens,Nr({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),d=Le();de(l);let p=!1;const f=()=>{p||(p=!0,l.remove(),d())},g=I=>{f(),r(I)},w=()=>{f(),r(null)},m=I=>{f(),t(I)},x=l.querySelector(".__crossx-card");this.applyPinKeyboardMode(x),(S=x.querySelector("#__crossx-close-btn"))==null||S.addEventListener("click",w),Cr(x,g,w,m,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",I=>{I.target===l&&w()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var c;le();const t=xl(this.tokens,e);de(t);const n=()=>t.remove(),i=l=>{n(),r(l)},o=()=>{n(),r(null)},a=t.querySelector(".__crossx-card");a&&this.applyPinKeyboardMode(a),Al(t,i,o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.addEventListener("click",l=>{l.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;le();const{overlay:n,startCountdown:i}=ml(this.tokens,e,r);de(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;le();const t=Xc(e,this.tokens,this.messages);de(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var f;d.stopPropagation();const p=l.dataset.copy;p&&((f=navigator.clipboard)==null||f.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{le();const n=Zc(e,this.tokens,this.messages);de(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var d,p;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",f=>{f.target===n&&a()});const l=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(Qc(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,d,p;le();let t;e.type==="sign-message"?t=el(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=tl(e,this.tokens,this.messages):e.type==="sign"?t=Hc(e,this.tokens,this.displayDecimals,this.messages):t=Vc(e,this.tokens,this.displayDecimals,this.messages);const n=Le();de(t);const i=()=>{t.remove(),n()},o=()=>{i(),r(!0)},a=()=>{i(),r(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(d=t.querySelector("#__crossx-cancel-btn"))==null||d.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",g=>{var m;g.stopPropagation();const w=f.dataset.copy;w&&((m=navigator.clipboard)==null||m.writeText(w).catch(()=>{}))})}),Nc(t),t.addEventListener("click",f=>{f.target===t&&a()});const c=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Rl{constructor(e,r,t,n=()=>!1){this.browserConfirmation=e,this.getBridge=r,this.getOrigin=t,this.isAuthenticatedViaRNBridge=n}shouldDelegateToBridge(){var e;return this.isAuthenticatedViaRNBridge()&&!!((e=this.getBridge())!=null&&e.isInstalled)}async requestConfirmation(e){return this.shouldDelegateToBridge()?!0:this.browserConfirmation.requestConfirmation(e)}async requestNativeConfirmation(e){const r=this.getBridge();if(!r)return{approved:!1,reason:"Bridge not available"};const{operation:t,payload:n,chainId:i}=this.mapToNativeParams(e),o={operation:t,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await r.requestUserConfirmation(o)}mapToNativeParams(e){const r=e.type;switch(r){case"sign-message":{const t=e;return{operation:"signMessage",payload:{message:t.message,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign-typed-data":{const t=e;return{operation:"signTypedData",payload:{typedData:t.typedData,from:t.from,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"sign":{const t=e;return{operation:"signTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}case"send":{const t=e;return{operation:"sendTransaction",payload:{from:t.from,to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nativeSymbol:t.nativeSymbol,nativeDecimals:t.nativeDecimals,dappName:t.dappName,accountName:t.accountName},chainId:t.chainId}}default:throw new _(h.INVALID_CONFIG,`Unknown confirmation type: ${String(r)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,r){if(this.shouldDelegateToBridge()){try{await r}catch{}return}return this.browserConfirmation.showTransactionProgress(e,r)}async showLoginSelector(e){return this.browserConfirmation.showLoginSelector(e)}async showMigrationFoundPrompt(e){return this.browserConfirmation.showMigrationFoundPrompt(e)}async showRecoveryPinInputPrompt(e){return this.browserConfirmation.showRecoveryPinInputPrompt(e)}async showRecoveryPinLockedPrompt(e,r){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,r)}async showWalletSelector(e,r,t,n){const i=this.getBridge();if(this.shouldDelegateToBridge()&&(i!=null&&i.showWalletSelector))try{const o=await i.showWalletSelector({requiredAddress:t}),a=e.find(c=>c.address.toLowerCase()===o.address.toLowerCase());return{address:o.address,index:(a==null?void 0:a.index)??o.index,name:a==null?void 0:a.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t,n)}async showWalletCreatedPrompt(){var e,r;if(!this.shouldDelegateToBridge())return((r=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:r.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}showUpdateRequired(e){return this.browserConfirmation.showUpdateRequired(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,r){return this.browserConfirmation.setTheme(e,r)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var r,t;(t=(r=this.browserConfirmation).setPinKeyboard)==null||t.call(r,e)}}class $n{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}const Nl=new WeakMap;function Cl(s,e){Nl.set(s,e)}function Un(s){return Ol(s)}function Ol(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
6
+ For security, you must continue with the same account.`,update_required_title:"Update required",update_required_message:"This service is using a wallet version that is no longer supported, so you cannot sign in or send transactions right now. Please try again after the service is updated.",update_required_confirm_button:"OK",session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},Qn={ko:kr,en:Wt};function we(s="en",e){return Qn[s]??Wt}function ei(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const Lr="crossx_access_token",Ur="crossx_refresh_token",Wr="crossx_user_info",vt=class vt{constructor(e,t,r,n,i,a,o,c,u=()=>{}){this.config=e,this.storage=t,this.crypto=r,this.oauth=n,this.transport=i,this.walletProvider=a,this.tokenStore=o,this.requestFreshTokenFromBridge=c,this.getLocale=u,this._refreshPromise=null,this._migrated=!1;const f=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${f}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${f}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${f}_user_info`,this.STORAGE_KEY_RN_BRIDGE_SESSION=`crossx_${f}_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 t=this.crypto.decodeJWT(e);return t!=null&&t.exp?t.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 t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const r=t;if(r.code&&r.code!==200&&r.code>0)return{code:r.code,message:r.message??""}}return null}checkResponseError(e,t){const r=this.extractResponseErrorCode(e);if(r)throw new h(l.AUTH_FAILED,`${t} 실패 (코드 ${r.code}): ${r.message}`)}async execute(e){let t,r;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:a,legacyOauthServiceUrl:o}=this.config,c=ei(this.getLocale()),u=E=>{const m=`${E}${i}`,y=m.includes("?")?"&":"?";return`${m}${y}locale=${c}`},f=u(a),g=o?u(o):void 0;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${f}`);const S=await this.oauth.openAuth({authUrl:f,...g?{legacyAuthUrl:g}:{},expectedOrigin:new URL(a).origin});t=S.token,r=S.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",t.length,")"),r&&d.log("[CROSSx] OAuth 콜백 email:",r)}catch(n){if(d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n),n instanceof h)throw n;const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new h(l.OAUTH_POPUP_BLOCKED,i):new h(l.AUTH_FAILED,i)}return this.processFirebaseToken(t,r)}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 r,n,i;let t;try{const{authApiUrl:a}=this.config,{accessToken:o}=await this.exchangeNativeFirebaseToken(e.idToken,a);let c,u;try{const f=this.crypto.decodeJWT(e.idToken);u=e.provider??((r=f.firebase)==null?void 0:r.sign_in_provider);const g=((n=f.firebase)==null?void 0:n.identities)??{};c=f.email??((i=g.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",u,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(o){const f=await this.crypto.verifyJWT(o);if(!f.valid)throw new h(l.AUTH_FAILED,"Access token 검증 실패");const g=f.payload;t={id:g.sub,email:g.email??c,signInProvider:u,providerSub:e.providerSub},this.tokenStore.set(o),await this.storage.set(this.STORAGE_KEY_RN_BRIDGE_SESSION,!0),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,o),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,t)}else throw new h(l.AUTH_FAILED,"Access token 교환 실패")}catch(a){const o=a instanceof Error?a.message:String(a),c=a instanceof Error?a.stack:void 0,u=a instanceof Error?a.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",u,"message:",o,"stack:",c),{success:!1,error:o||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,!1)}async processFirebaseToken(e,t){var i,a,o,c,u;let r,n=!1;try{const{authApiUrl:f}=this.config,{accessToken:g,refreshToken:S}=await this.exchangeFirebaseToken(e,f);let E,m,y;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),m=(i=A.firebase)==null?void 0:i.sign_in_provider;const P=((a=A.firebase)==null?void 0:a.identities)??{};y=A.email??((o=P.email)==null?void 0:o[0]),m==="google.com"?E=(c=P["google.com"])==null?void 0:c[0]:m==="apple.com"&&(E=(u=P["apple.com"])==null?void 0:u[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",m,"hasProviderSub:",!!E,"email:",y??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(g){const A=this.crypto.decodeJWT(g);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const P=await this.crypto.verifyJWT(g);if(n=P.signatureVerified??!1,!P.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const F=P.payload,M=F.email??y??t;d.log("[CROSSx] email 소스 — CROSSx JWT:",F.email??"(없음)","/ Firebase JWT:",y??"(없음)","/ OAuth 콜백:",t??"(없음)","→",M??"(없음)"),r={id:F.sub,email:M,signInProvider:m,providerSub:E},this.tokenStore.set(g),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,g),S&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,S):S&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);r={id:A.sub,email:A.email??t,signInProvider:m,providerSub:E},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",r.id)}d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)");const w=this.useCookieAuth?{id:r.id,email:r.email,signInProvider:r.signInProvider,providerSub:r.providerSub}:r;await this.storage.set(this.STORAGE_KEY_USER,w),await this.clearStoredRNBridgeSession(),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(f){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",f),{success:!1,error:f instanceof Error?f.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,n)}async exchangeNativeFirebaseToken(e,t){const r=`${t}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",r,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:r,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(o){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",r,"error:",o);const c=o instanceof Error?o.message:String(o);throw new h(l.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,o)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const a=this.extractAccessToken(i);if(!a)throw new h(l.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:a}}async exchangeFirebaseToken(e,t){const r=this.useCookieAuth,n=r?`${t}/cross-auth/social/login/cookie`:`${t}/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"},...r?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Token exchange");const o=this.extractAccessToken(a);if(r&&!o)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!o)throw new h(l.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return r||(c=this.extractRefreshToken(a)),{accessToken:o,refreshToken:c}}extractAccessToken(e){const t=(e==null?void 0:e.data)??e;if(this.isJwtString(t))return t;if(typeof t=="object"&&t!==null){const r=t;if(this.isJwtString(r.data))return r.data;if(typeof r.data=="object"&&r.data!==null){const i=r.data,a=i.access_token??i.token;if(typeof a=="string")return a}const n=r.access_token??r.token;if(typeof n=="string")return n}}extractRefreshToken(e){const t=(e==null?void 0:e.data)??e;if(typeof t!="object"||t===null)return;const r=t;if(typeof r.data=="object"&&r.data!==null){const i=r.data,a=i.refresh_token??i.refresh;if(typeof a=="string")return a}const n=r.refresh_token??r.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 r=await this.crypto.verifyJWT(e);if(r.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,r.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const r=await this.silentRefresh();r&&this.tokenStore.set(r)}else{const r=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:",r?"있음":"없음","refresh_token:",n?"있음":"없음"),n){r&&this.tokenStore.set(r);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!r)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(r)).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(r)}}const t=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",t?`있음 (id: ${t.id})`:"없음"),!t)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",t.id);try{return await this.loadWallet(t,!1)}catch(r){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",r),{success:!0,user:t,tokenSignatureVerified:!1}}}catch(e){const t=e instanceof h&&e.code===l.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",t?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),t&&(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:t}=this.config,r=this.useCookieAuth,n=`${t}/cross-auth/social/refresh/simple`,i={};if(!r){const f=this.tokenStore.get()??"";f&&(i.access_token=f),e&&(i.refresh_token=e)}const a=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...r?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",a.status);const o=a.data,c=this.extractResponseErrorCode(o);if(c){const f=vt.REFRESH_RELOGIN_CODES.has(c.code);throw new h(f?l.SESSION_EXPIRED:l.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const u=this.extractAccessToken(o);if(r&&!u){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!u)throw new h(l.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(u),!r){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,u);const f=this.extractRefreshToken(o);f&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,f)}return d.log("[CROSSx] silentRefresh 성공"),u}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge&&await this.hasStoredRNBridgeSession()){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const r=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(r.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(r){throw r instanceof h&&r.code===l.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),r}}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 h&&e.code===l.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,t){let r,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!t)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const o=await this.silentRefresh(t);if(!o)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=o,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 a=i.payload;d.log("[CROSSx] signInWithJWT — sub:",a.sub,"signatureVerified:",n),r={id:a.sub,email:a.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),t&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,t),await this.clearStoredRNBridgeSession()),await this.storage.set(this.STORAGE_KEY_USER,r),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(r,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Wr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const r=await this.storage.get(Lr);r&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,r);const n=await this.storage.get(Ur);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Wr),await this.storage.remove(Lr),await this.storage.remove(Ur),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,t){let r,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 a=await this.walletProvider.getAddresses(e.id);a.length>0?(r=a[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",r)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(a){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",a)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),r=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",r)}catch(i){if(i instanceof h&&i.code===l.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof h&&(i.code===l.PROJECT_NOT_REGISTERED||i.code===l.PROJECT_ID_MISSING||i.code===l.ORIGIN_NOT_ALLOWED||i.code===l.SDK_VERSION_UNSUPPORTED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",r,"needsMigration:",n),{success:!0,address:r,user:e,needsMigration:n,tokenSignatureVerified:t}}};vt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Bt=vt;class ti{constructor(e,t,r,n=[]){this.config=e,this.storage=t,this.tokenStore=r,this.preservedKeys=n;const i=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${i}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${i}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${i}_user_info`}async hasStoredSession(){const e=[this.STORAGE_KEY_ACCESS_TOKEN,this.STORAGE_KEY_REFRESH_TOKEN,this.STORAGE_KEY_USER];for(const t of e){const r=await this.storage.get(t).catch(()=>null);if(r!=null)return!0}return!1}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER);const e=[];for(const t of this.preservedKeys){const r=await this.storage.get(t).catch(()=>null);r!=null&&e.push([t,r])}await this.storage.clear();for(const[t,r]of e)await this.storage.set(t,r).catch(()=>{})}}class ri{constructor(e,t){this.storage=e,this.walletProvider=t}async execute(e,t){if(!this.walletProvider.migrateWallet)throw new h(l.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",t);const r=await this.walletProvider.migrateWallet(e,t);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",r.address),{address:r.address}}}class Mt{constructor(){this.encryptedBytes=null,this.xorKey=null,this.setAt=null}set(e){this.clear();const t=new TextEncoder().encode(e),r=new Uint8Array(t.length);crypto.getRandomValues(r);const n=new Uint8Array(t.length);for(let i=0;i<t.length;i++)n[i]=t[i]^r[i];t.fill(0),this.xorKey=r,this.encryptedBytes=n,this.setAt=Date.now()}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let r=0;r<this.encryptedBytes.length;r++)e[r]=this.encryptedBytes[r]^this.xorKey[r];const t=new TextDecoder().decode(e);return e.fill(0),t}clear(){var e,t;(e=this.encryptedBytes)==null||e.fill(0),(t=this.xorKey)==null||t.fill(0),this.encryptedBytes=null,this.xorKey=null,this.setAt=null}getSetAt(){return this.setAt}has(){return this.encryptedBytes!==null}}const si="/authorize/result",ni="one-oauth:authorization_response",Br="one-oauth:authorization_error",ii="one-oauth:authorization_ack",ai="openid profile offline_access";function Ft(s){let e="";for(const t of s)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Mr(s=32){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ft(e)}async function Fr(s){const e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s));return Ft(new Uint8Array(e))}function dt(s=16){const e=new Uint8Array(s);return crypto.getRandomValues(e),Ft(e)}const oi=300*1e3,ci=600*1e3,Kt="crossx.oneid.pending",li=1e3,di=10;function Kr(s){switch(s){case"access_denied":return l.USER_REJECTED;case"required_items_not_agreed":return l.ONEID_TERMS_NOT_AGREED;case"account_not_found":return l.ONEID_ACCOUNT_NOT_FOUND;case"service_not_linked":return l.ONEID_SERVICE_NOT_LINKED;default:return l.ONEID_AUTHORIZATION_FAILED}}function hi(s){switch(s){case"session_evicted":return l.ONEID_SESSION_EVICTED;case"session_revoked":return l.ONEID_SESSION_REVOKED;case"session_expired":return l.ONEID_SESSION_EXPIRED;default:return l.ONEID_SESSION_INVALID}}function Ht(s){if(!(typeof s!="string"||!s.startsWith("/"))&&!(s.startsWith("//")||s.startsWith("/\\")))return s}function We(s){let e;try{e=new URL(s)}catch{throw new h(l.INVALID_CONFIG,"ONE ID issuer가 올바른 URL이 아닙니다")}return e.toString().replace(/\/+$/,"")}function Hr(s){const e=s.split(".")[1];if(!e)return null;try{const t=e.replace(/-/g,"+").replace(/_/g,"/"),r=t+"=".repeat((4-t.length%4)%4),n=new TextDecoder().decode(Uint8Array.from(atob(r),a=>a.charCodeAt(0))),i=JSON.parse(n);return typeof i=="object"&&i!==null?i:null}catch{return null}}function ui(s){if(typeof s!="object"||s===null)return!1;const e=s.type;return e===ni||e===Br}function Gr(s,e){if(typeof s.access_token!="string"||s.access_token==="")throw new h(l.ONEID_AUTHORIZATION_FAILED,"토큰 응답에 access_token이 없습니다");const t=typeof s.expires_in=="number"?s.expires_in:0;return{accessToken:s.access_token,tokenType:typeof s.token_type=="string"?s.token_type:"Bearer",expiresAt:e+t*1e3,refreshToken:typeof s.refresh_token=="string"?s.refresh_token:void 0,idToken:typeof s.id_token=="string"?s.id_token:void 0,scope:typeof s.scope=="string"?s.scope:void 0}}class fi{constructor(){this.reason=null,this.onAbort=null}abort(e){var t;this.reason??(this.reason=e),(t=this.onAbort)==null||t.call(this,e)}throwIfAborted(){if(this.reason!==null)throw new h(l.USER_REJECTED,this.reason)}}class gi{constructor(e={}){this.abortPending=null,this.popupSeq=0,this.options=e}get fetchImpl(){return this.options.fetch??((e,t)=>fetch(e,t))}now(){var e,t;return((t=(e=this.options).now)==null?void 0:t.call(e))??Date.now()}get pendingStorage(){return this.options.pendingStorage??window.sessionStorage}cancelPending(e="ONE ID 로그인 대기를 중단했습니다"){var t;(t=this.abortPending)==null||t.call(this,e)}async authorize(e){let t=null;if(e.mode!=="redirect"&&(t=this.openBlankPopup(e.width,e.height),!t&&e.mode==="popup"))throw new h(l.OAUTH_POPUP_BLOCKED,"팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요.");try{const r=We(e.issuer);if(!e.clientId)throw new h(l.INVALID_CONFIG,"ONE ID clientId가 비어 있습니다");this.cancelPending("새 ONE ID 로그인 요청으로 이전 대기를 중단했습니다");const n=new fi,i=a=>n.abort(a);this.abortPending=i;try{return t?await this.authorizeWithPopup(t,{...e,issuer:r},n):await this.authorizeWithRedirect({...e,issuer:r},n)}finally{this.abortPending===i&&(this.abortPending=null)}}catch(r){try{t==null||t.close()}catch{}throw r}}async completeRedirect(e,t){const r=We(e.issuer),n=this.takePending(),i=new URL(t).searchParams;if(!n||n.issuer!==r||n.clientId!==e.clientId)throw new h(l.ONEID_STATE_MISMATCH,"진행 중인 ONE ID 로그인이 없습니다. 다시 로그인해 주세요.");if(this.now()-n.createdAt>ci)throw new h(l.ONEID_TIMEOUT,"ONE ID 로그인 시간이 지났습니다");const a=i.get("state");if(!a||a!==n.state)throw new h(l.ONEID_STATE_MISMATCH,"ONE ID 로그인 결과의 state가 다릅니다");if(i.get("iss")!==r)throw new h(l.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다");const o=i.get("error");if(o){const f=i.get("error_description")??void 0;throw new h(Kr(o),f||`ONE ID 인가 오류: ${o}`,{error:o,error_description:f})}const c=i.get("code");if(!c)throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다");return{tokens:await this.exchangeCode({...e,issuer:r},c,n.codeVerifier,n.redirectUri,n.nonce),returnTo:Ht(n.returnTo)}}async refresh(e,t){const r=We(e.issuer),n=new URLSearchParams({grant_type:"refresh_token",client_id:e.clientId,refresh_token:t});let i;try{i=await this.fetchImpl(`${r}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:n})}catch(c){throw new h(l.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",c)}const a=await Gt(i);if(!i.ok){if(i.status===400&&a.error==="invalid_grant"){const c=typeof a.error_reason=="string"?a.error_reason:void 0;throw new h(hi(c),"ONE ID 세션이 끝났습니다. 다시 로그인해 주세요.",{error:"invalid_grant",error_reason:c})}throw i.status>=400&&i.status<500&&i.status!==408&&i.status!==429?new h(l.ONEID_SESSION_INVALID,"ONE ID 세션을 갱신할 수 없습니다. 다시 로그인해 주세요.",{status:i.status,error:a.error}):new h(l.NETWORK_ERROR,"ONE ID 세션을 갱신하지 못했습니다",{status:i.status,error:a.error})}const o=Gr(a,this.now());return{...o,refreshToken:o.refreshToken??t}}async logout(e,t){const r=We(e.issuer);let n;try{n=await this.fetchImpl(`${r}/logout`,{method:"POST",headers:{Authorization:`Bearer ${t}`}})}catch(i){throw new h(l.NETWORK_ERROR,"ONE ID 로그아웃 요청을 보내지 못했습니다",i)}if(!n.ok&&n.status!==401)throw new h(l.NETWORK_ERROR,"ONE ID 로그아웃 요청이 실패했습니다",{status:n.status})}openBlankPopup(e=500,t=700){const r=Math.max(e,500),n=Math.max(t,700),i=window.screenX+(window.outerWidth-r)/2,a=window.screenY+(window.outerHeight-n)/2;try{return this.popupSeq+=1,window.open("about:blank",`ONEidLogin${this.popupSeq}`,`width=${r},height=${n},left=${i},top=${a}`)}catch{return null}}async pushAuthorizationRequest(e,t,r,n,i){const a=new URLSearchParams({client_id:e.clientId,response_type:"code",redirect_uri:t,scope:e.scope??ai,state:r,nonce:n,code_challenge:i,code_challenge_method:"S256"});let o;try{o=await this.fetchImpl(`${e.issuer}/par`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a})}catch(u){throw new h(l.NETWORK_ERROR,"ONE ID 로그인 요청을 보내지 못했습니다",u)}const c=await Gt(o);if(!o.ok||typeof c.request_uri!="string")throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 요청이 거부되었습니다",{status:o.status,error:c.error});return c.request_uri}authorizeUrl(e,t){const r=new URL(`${e.issuer}/authorize`);return r.searchParams.set("client_id",e.clientId),r.searchParams.set("request_uri",t),r.toString()}async exchangeCode(e,t,r,n,i){const a=new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:t,redirect_uri:n,code_verifier:r});let o;try{o=await this.fetchImpl(`${e.issuer}/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:a})}catch(f){throw new h(l.NETWORK_ERROR,"ONE ID 토큰을 받지 못했습니다",f)}const c=await Gt(o);if(!o.ok)throw new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 토큰 교환이 거부되었습니다",{status:o.status,error:c.error});const u=Gr(c,this.now());if(u.idToken){const f=Hr(u.idToken);if(!f||f.iss!==e.issuer||f.nonce!==i)throw new h(l.ONEID_ISSUER_MISMATCH,"ONE ID id_token의 발급자나 nonce가 요청과 다릅니다")}return u}async authorizeWithPopup(e,t,r){const n=new URL(t.issuer).origin,i=`${t.issuer}${si}`,a=dt(),o=dt(),c=Mr(),u=await Fr(c),f=await this.pushAuthorizationRequest(t,i,a,o,u);r.throwIfAborted(),d.log("[CROSSx] ONE ID 로그인 팝업 이동",{issuer:t.issuer,clientId:t.clientId}),e.location.href=this.authorizeUrl(t,f);const g=await new Promise((E,m)=>{let y=0,w=!0;const A=()=>{r.onAbort=null,clearTimeout(F),clearInterval(M),window.removeEventListener("message",V)},P=U=>{A(),m(U)},F=setTimeout(()=>{P(new h(l.ONEID_TIMEOUT,"ONE ID 로그인 응답 시간이 지났습니다"))},oi),M=setInterval(()=>{if(!w)return;y++;let U;try{U=e.closed}catch{w=!1;return}if(!U)return;const H=typeof document<"u"&&document.hasFocus();if(y<=di&&!H){d.warn("[CROSSx] ONE ID 팝업 closed 오탐 가능성(COOP) — 결과 대기 유지"),w=!1;return}P(new h(l.USER_REJECTED,"ONE ID 로그인이 취소되었습니다"))},li),V=U=>{if(U.origin!==n||U.source!==e||!ui(U.data))return;const H=U.data;if(H.state!==a){d.warn("[CROSSx] ONE ID 결과 state가 현재 요청과 달라 무시합니다");return}try{e.postMessage({type:ii,state:a},n)}catch{}if(H.iss!==t.issuer){P(new h(l.ONEID_ISSUER_MISMATCH,"ONE ID 로그인 결과의 발급자가 다릅니다"));return}if(H.type===Br||H.error){const Z=H.error??"unknown_error";d.warn("[CROSSx] ONE ID 인가 오류:",Z),P(new h(Kr(Z),H.error_description||`ONE ID 인가 오류: ${Z}`,{error:Z,error_description:H.error_description}));return}if(!H.code){P(new h(l.ONEID_AUTHORIZATION_FAILED,"ONE ID 로그인 결과에 code가 없습니다"));return}A(),E(H.code)};r.onAbort=U=>{P(new h(l.USER_REJECTED,U))},window.addEventListener("message",V)}),S=await this.exchangeCode(t,g,c,i,o);return d.log("[CROSSx] ONE ID 로그인 완료 (팝업)"),{status:"completed",tokens:S,returnTo:Ht(t.returnTo)}}async authorizeWithRedirect(e,t){const r=e.redirectUri??`${window.location.origin}/auth/callback`;if(new URL(r).origin!==window.location.origin)throw new h(l.INVALID_CONFIG,"ONE ID redirectUri는 지금 페이지와 같은 origin이어야 합니다");const n=dt(),i=dt(),a=Mr(),o=await Fr(a),c=await this.pushAuthorizationRequest(e,r,n,i,o);t.throwIfAborted();const u={issuer:e.issuer,clientId:e.clientId,state:n,nonce:i,codeVerifier:a,redirectUri:r,returnTo:Ht(e.returnTo),createdAt:this.now()};this.pendingStorage.setItem(Kt,JSON.stringify(u)),d.log("[CROSSx] ONE ID 로그인 같은 창 이동",{issuer:e.issuer,clientId:e.clientId});const f=this.authorizeUrl(e,c);return(this.options.navigate??(g=>window.location.assign(g)))(f),{status:"redirecting"}}takePending(){const e=this.pendingStorage.getItem(Kt);if(this.pendingStorage.removeItem(Kt),!e)return null;try{const t=JSON.parse(e);return typeof(t==null?void 0:t.state)=="string"&&typeof t.codeVerifier=="string"?t:null}catch{return null}}}async function Gt(s){try{const e=await s.json();return typeof e=="object"&&e!==null?e:{}}catch{return{}}}const ht="crossx.oneid.session",$r=60*1e3,$t=new Set([l.ONEID_SESSION_EVICTED,l.ONEID_SESSION_REVOKED,l.ONEID_SESSION_EXPIRED,l.ONEID_SESSION_INVALID]);function Vr(s){return s instanceof h&&$t.has(s.code)}class _i{constructor(e,t,r,n=()=>Date.now()){this.port=e,this.config=t,this.storage=r,this.now=n,this.refreshing=null,this.generation=0}save(e){this.generation+=1;const t={issuer:We(this.config.issuer),clientId:this.config.clientId,tokens:e};return this.storage.setItem(ht,JSON.stringify(t)),Jr(t)}async get(){const e=await this.ensureFresh();return e?Jr(e):null}async getAccessToken(){const e=await this.ensureFresh();if(!e)throw new h(l.AUTH_NOT_AUTHENTICATED,"ONE ID로 로그인하지 않았습니다");return e.tokens.accessToken}async signOut(){const e=this.read();if(this.clear(),!e)return;let t=e.tokens.accessToken;if(e.tokens.refreshToken&&e.tokens.expiresAt-$r<=this.now())try{t=(await this.port.refresh(this.config,e.tokens.refreshToken)).accessToken}catch(r){if(r instanceof h&&$t.has(r.code))return}await this.port.logout(this.config,t)}clear(){this.generation+=1,this.storage.removeItem(ht)}read(){var t;const e=this.storage.getItem(ht);if(!e)return null;try{const r=JSON.parse(e);return typeof((t=r==null?void 0:r.tokens)==null?void 0:t.accessToken)=="string"&&typeof r.tokens.expiresAt=="number"&&r.issuer===We(this.config.issuer)&&r.clientId===this.config.clientId?r:(this.clear(),null)}catch{return this.clear(),null}}async ensureFresh(){const e=this.read();if(!e)return null;if(e.tokens.expiresAt-$r>this.now())return e;if(!e.tokens.refreshToken){if(e.tokens.expiresAt>this.now())return e;throw this.clear(),new h(l.ONEID_SESSION_EXPIRED,"ONE ID 로그인이 만료되었습니다. 다시 로그인해 주세요.")}return this.refreshing??(this.refreshing=this.refresh(e).finally(()=>{this.refreshing=null})),this.refreshing}async refresh(e){const t=this.generation;try{const r=await this.port.refresh(this.config,e.tokens.refreshToken),n={...e,tokens:r};if(t!==this.generation)throw new h(l.AUTH_NOT_AUTHENTICATED,"ONE ID 세션이 바뀌었습니다");return this.storage.setItem(ht,JSON.stringify(n)),n}catch(r){if(t!==this.generation)throw r;if(r instanceof h&&$t.has(r.code))throw this.clear(),r;if(e.tokens.expiresAt>this.now())return e;throw r}}}function Jr(s){const e=s.tokens.idToken?Hr(s.tokens.idToken):null;return{subject:typeof(e==null?void 0:e.sub)=="string"?e.sub:"",clientId:s.clientId,issuer:s.issuer,scope:s.tokens.scope,expiresAt:s.tokens.expiresAt}}function pi(s){return s==="local"?window.localStorage:window.sessionStorage}const wi=new TextEncoder;function j(s){return wi.encode(s)}function Se(...s){const e=new Uint8Array(s.reduce((r,n)=>r+n.length,0));let t=0;for(const r of s)e.set(r,t),t+=r.length;return e}function Si(s){return new Uint8Array([s>>>24&255,s>>>16&255,s>>>8&255,s&255])}function oe(s){let e="";for(const t of s)e+=String.fromCharCode(t);return btoa(e)}function Be(s){const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}function Vt(s){return oe(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ei(s){let e=s.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";return Be(e)}function mi(s){return globalThis.crypto.getRandomValues(new Uint8Array(s))}async function qr(s){return new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",s))}const ie=globalThis.crypto.subtle,Jt={name:"ECDH",namedCurve:"P-256"},yi=32,Ai=12,Ii=32;function Xe(s){return new Uint8Array([s>>>8&255,s&255])}const je=Se(j("HPKE"),Xe(16),Xe(1),Xe(2)),Yr=Se(j("KEM"),Xe(16)),xe=new Uint8Array(0);async function zr(s,e){const t=s.length===0?new Uint8Array(32):s,r=await ie.importKey("raw",t,{name:"HMAC",hash:"SHA-256"},!1,["sign"]);return new Uint8Array(await ie.sign("HMAC",r,e))}async function Ti(s,e,t){const r=new Uint8Array(t);let n=xe;for(let i=1,a=0;a<t;i++)n=await zr(s,Se(n,e,new Uint8Array([i]))),r.set(n.subarray(0,Math.min(32,t-a)),a),a+=32;return r}function ut(s,e,t,r){return zr(s,Se(j("HPKE-v1"),r,j(e),t))}function qt(s,e,t,r,n){return Ti(s,Se(Xe(r),j("HPKE-v1"),n,j(e),t),r)}async function Xr(s,e){const t=await ie.importKey("raw",e,Jt,!1,[]);return new Uint8Array(await ie.deriveBits({name:"ECDH",public:t},s,256))}async function jr(s,e,t){const r=await ut(xe,"eae_prk",s,Yr);return qt(r,"shared_secret",Se(e,t),Ii,Yr)}async function Zr(s){const e=await ut(xe,"psk_id_hash",xe,je),t=await ut(xe,"info_hash",xe,je),r=Se(new Uint8Array([0]),e,t),n=await ut(s,"secret",xe,je),i=await qt(n,"key",r,yi,je),a=await qt(n,"base_nonce",r,Ai,je);return{key:i,baseNonce:a}}function ft(s,e){if(s.length!==65||s[0]!==4)throw new Error(`${e} must be SEC1 uncompressed P-256 (65B)`)}async function Qr(){const s=await ie.generateKey(Jt,!1,["deriveBits"]),e=new Uint8Array(await ie.exportKey("raw",s.publicKey));return{privateKey:s.privateKey,publicKey:e}}async function Ri(s,e,t){ft(s,"recipient public key");const r=await ie.generateKey(Jt,!0,["deriveBits"]),n=new Uint8Array(await ie.exportKey("raw",r.publicKey)),i=await jr(await Xr(r.privateKey,s),n,s),{key:a,baseNonce:o}=await Zr(i),c=await ie.importKey("raw",a,"AES-GCM",!1,["encrypt"]),u=new Uint8Array(await ie.encrypt({name:"AES-GCM",iv:o,additionalData:t},c,e));return{enc:n,ciphertext:u}}async function Oi(s,e,t,r){ft(e,"enc");const n=await jr(await Xr(s.privateKey,e),e,s.publicKey),{key:i,baseNonce:a}=await Zr(n),o=await ie.importKey("raw",i,"AES-GCM",!1,["decrypt"]);return new Uint8Array(await ie.decrypt({name:"AES-GCM",iv:a,additionalData:r},o,t))}const es=globalThis.crypto.subtle,Ni={name:"ECDSA",namedCurve:"P-256"},Pi="one-wallet/authz-sig/v1",bi="one-wallet/seal-aad/v1",xi=60,vi=32,Ci={generate:1,recover:3,verify_pin:4,change_pin:5,get_address:10,get_mnemonic:11,get_private_key:12,get_share_c:13,activate:14,sign:20,sign_typed_data:21,sign_message:22};function Di(s){return Se(Si(s.length),s)}function ts(s,e,t){return Se(j(s),...e.map(Di),new Uint8Array([t]))}function ki(s,e,t){return ts(bi,[s.nonce,j(s.expiresAt),s.intentHash,j(e),j(s.authzKeyId)],t)}function Li(s,e,t){return ts(Pi,[s.enc,s.ciphertext,s.nonce,j(s.expiresAt),s.intentHash,j(e),j(s.authzKeyId)],t)}function Ui(s,e,t){return qr(ki(s,e,t))}function Wi(s){return s.toISOString().replace(/\.\d+Z$/,"Z")}async function Bi(s,e){if(s.length!==32)throw new Error("authz private key must be a 32B P-256 scalar");return ft(e,"authz public key"),es.importKey("jwk",{kty:"EC",crv:"P-256",x:Vt(e.subarray(1,33)),y:Vt(e.subarray(33,65)),d:Vt(s),ext:!1},Ni,!1,["sign"])}async function Mi(s){if(s.intent.command!==s.command)throw new Error("intent.command must match command");const e=Ci[s.command],t=j(JSON.stringify(s.intent)),r={nonce:mi(vi),expiresAt:Wi(new Date((s.now??new Date).getTime()+(s.ttlSec??xi)*1e3)),intentHash:await qr(t),authzKeyId:s.authz.keyId},n=await Ui(r,s.bindingId,e),i={pin:s.plaintext.pin};s.plaintext.new_pin!=null&&(i.new_pin=s.plaintext.new_pin),s.plaintext.share_c&&(i.share_c=oe(s.plaintext.share_c)),s.plaintext.response_key&&(i.response_key=oe(s.plaintext.response_key));const{enc:a,ciphertext:o}=await Ri(s.recipientPub,j(JSON.stringify(i)),n),c=new Uint8Array(await es.sign({name:"ECDSA",hash:"SHA-256"},s.authz.signingKey,Li({...r,enc:a,ciphertext:o},s.bindingId,e)));return{envelope:{enc:oe(a),ciphertext:oe(o),nonce:oe(r.nonce),expires_at:r.expiresAt,intent_hash:oe(r.intentHash),authz_key_id:r.authzKeyId,authz_sig:oe(c),authz_key_cert:s.authz.cert},intent:oe(t),aad:n}}function rs(s,e,t){return Oi(s,Be(e.enc),Be(e.ciphertext),t)}const Fi=90*1e3;class Ki{constructor(e){this.opts=e,this.current=null,this.pending=null,this.generation=0,this.now=e.now??Date.now}async get(){const e=this.current;return e&&e.expiresAtMs-this.now()>Fi?e:(this.pending??(this.pending=this.issue().finally(()=>{this.pending=null})),this.pending)}invalidate(){this.current=null}async revoke(){const e=this.current;if(this.generation++,this.current=null,this.pending=null,!!e)try{await this.opts.client.call("DELETE",`/authz-keys/${encodeURIComponent(e.keyId)}`)}catch{}}async issue(){var u;const e=this.generation,t=await Qr(),r=await this.opts.getIssuanceJwt(),n=await this.opts.client.call("POST","/authz-keys",{jwt:r,response_key:oe(t.publicKey)});if(!((u=n==null?void 0:n.key_cert)!=null&&u.key_id)||!n.cert_sig||!n.sealed_private_key)throw new h(l.AUTH_FAILED,"authz-keys response is incomplete");let i;try{i=await rs(t,n.sealed_private_key,Be(n.cert_sig))}catch(f){throw new h(l.AUTH_FAILED,"failed to open sealed authz key",{cause:f})}const a=await Bi(i,Be(n.key_cert.pubkey));i.fill(0);const o=Date.parse(n.key_cert.expires_at);if(Number.isNaN(o))throw new h(l.AUTH_FAILED,"authz key_cert has no valid expires_at");const c={signingKey:a,keyId:n.key_cert.key_id,cert:{...n.key_cert,sig:n.cert_sig},expiresAtMs:o};if(e!==this.generation)throw new h(l.AUTH_NOT_AUTHENTICATED,"authz key issuance was cancelled by sign-out");return this.current=c,c}}const Hi=600*1e3,Gi={UNAUTHORIZED:l.AUTH_TOKEN_INVALID,AUTHZ_TOKEN_INVALID:l.AUTH_TOKEN_INVALID,FORBIDDEN:l.AUTH_FAILED,AUTHZ_INVALID:l.AUTH_FAILED,OWNER_MISMATCH:l.AUTH_FAILED,USER_NOT_FOUND:l.USER_NOT_FOUND,INVALID_PIN:l.PIN_WRONG,PIN_LOCKED:l.PIN_LOCKED,PIN_THROTTLED:l.PIN_LOCKED,WALLET_ALREADY_EXISTS:l.WALLET_ALREADY_EXISTS,WALLET_NOT_FOUND:l.WALLET_NOT_FOUND,ADDRESS_NOT_FOUND:l.WALLET_NOT_FOUND,WALLET_DELETED:l.WALLET_NOT_FOUND,WALLET_NOT_ACTIVATED:l.WALLET_INCONSISTENT_STATE,WALLET_LOAD_FAILED:l.WALLET_INCONSISTENT_STATE,ADDRESS_LIMIT_EXCEEDED:l.ADDRESS_LIMIT_EXCEEDED,BROADCAST_FAILED:l.BROADCAST_FAILED,CHAIN_NOT_FOUND:l.CHAIN_NOT_SUPPORTED,INVALID_CHAIN_ID:l.INVALID_CHAIN,CHAIN_ID_MISMATCH:l.TYPED_DATA_CHAIN_ID_MISMATCH,INVALID_TYPED_DATA:l.TX_INVALID_PARAMS,INVALID_PARAMS:l.TX_INVALID_PARAMS,INVALID_REQUEST:l.TX_INVALID_PARAMS,BAD_REQUEST:l.TX_INVALID_PARAMS,INDEX_MISMATCH:l.TX_INVALID_PARAMS,OPERATION_IN_PROGRESS:l.GATEWAY_LOCK_CONFLICT,SIGNER_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,ATTESTATION_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,SERVICE_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,AUTH_UNAVAILABLE:l.GATEWAY_INTERNAL_ERROR,BAD_GATEWAY:l.GATEWAY_INTERNAL_ERROR,INTERNAL_ERROR:l.GATEWAY_INTERNAL_ERROR,ENVELOPE_INVALID:l.SIGNATURE_FAILED,REPLAY:l.SIGNATURE_FAILED};function $i(s,e){const t=(e==null?void 0:e.code)??"",r=Gi[t]??(s===401?l.AUTH_TOKEN_INVALID:s>=500?l.GATEWAY_INTERNAL_ERROR:l.UNKNOWN_ERROR),n={status:s,serverCode:t};return(e==null?void 0:e.remaining_attempts)!=null&&(n.remainingAttempts=e.remaining_attempts),(e==null?void 0:e.lock_expires_at)!=null&&(n.lockExpiresAt=e.lock_expires_at>1e10?e.lock_expires_at:e.lock_expires_at*1e3),(e==null?void 0:e.permanent)!=null&&(n.permanent=e.permanent),e!=null&&e.tx_hash&&(n.txHash=e.tx_hash),new h(r,(e==null?void 0:e.message)||`one-wallet-api ${s}${t?` ${t}`:""}`,n)}class Vi{constructor(e){this.opts=e,this.recipient=null,this.now=e.now??Date.now}async call(e,t,r){const n=await this.opts.getAccessToken();return this.send(e,t,r,{Authorization:`Bearer ${n}`})}async callPublic(e,t){return this.send(e,t,void 0,{})}async getRecipientKey(){if(this.recipient&&this.now()-this.recipient.fetchedAt<Hi)return this.recipient.key;const e=await this.callPublic("GET","/attestation");if(!(e!=null&&e.recipient_public_key))throw new h(l.GATEWAY_INTERNAL_ERROR,"attestation has no recipient_public_key");const t=Be(e.recipient_public_key);return ft(t,"recipient_public_key"),this.recipient={key:t,fetchedAt:this.now()},t}forgetRecipientKey(){this.recipient=null}async send(e,t,r,n){const i=typeof this.opts.baseUrl=="function"?this.opts.baseUrl():this.opts.baseUrl;if(!i)throw new h(l.INVALID_CONFIG,"one-wallet-api URL is not configured for this environment");let a;try{a=await this.opts.transport.request({url:`${i.replace(/\/+$/,"")}${t}`,method:e,headers:r===void 0?n:{...n,"Content-Type":"application/json"},body:r})}catch(o){throw new h(l.NETWORK_ERROR,"one-wallet-api request failed",{cause:o})}if(a.status<200||a.status>=300)throw $i(a.status,a.data);return a.data}}const Yt=s=>`m/44'/60'/0'/0/${s}`,Ji=/^0x(?:[0-9a-fA-F]{2})*$/;function qi(s){try{const e=JSON.parse(new TextDecoder().decode(Ei(s.split(".")[1]??"")));if(typeof(e==null?void 0:e.sub)=="string"&&e.sub)return e.sub}catch{}throw new h(l.AUTH_TOKEN_INVALID,"access token has no sub")}function Yi(s){if(Ji.test(s)){const e=s.slice(2);return Uint8Array.from({length:e.length/2},(t,r)=>parseInt(e.slice(r*2,r*2+2),16))}return j(s)}const ss=s=>`0x${s.toString(16)}`;function ns(s,e){const t=s.chainId??Number(e.split(":")[1]);if(!Number.isSafeInteger(t))throw new h(l.TX_INVALID_PARAMS,`invalid chain id: ${e}`);if(s.nonce===void 0)throw new h(l.TX_INVALID_PARAMS,"transaction nonce is required");const r={to:s.to,value:s.value??"0x0",data:s.data??"0x",gas_limit:s.gasLimit,gas_price:s.gasPrice,max_fee_per_gas:s.maxFeePerGas,max_priority_fee_per_gas:s.maxPriorityFeePerGas,nonce:ss(s.nonce),chain_id:ss(t)};return Object.fromEntries(Object.entries(r).filter(([,n])=>n!==void 0))}class is{constructor(e){this.opts=e,this.walletAddress=null,this.client=new Vi({baseUrl:e.baseUrl,transport:e.transport,getAccessToken:e.getAccessToken,now:e.now}),this.authzKeys=new Ki({client:this.client,getIssuanceJwt:e.getAccessToken,now:e.now})}async checkWallet(){return await this.findWallet()?"exists":"not_found"}async getOrCreateWallet(e){if(this.walletAddress)return this.walletData(this.walletAddress);const t=await this.findWallet();if(t)return this.walletData(t.address);const r=this.requirePin(),n=qi(await this.opts.getAccessToken()),i=await Qr(),{result:a,aad:o}=await this.withEnvelope("generate",n,{command:"generate"},{pin:r,response_key:i.publicKey},(c,u)=>this.client.call("POST","/wallets",{envelope:c,intent:u,ignore_backup:!1}));if(this.walletAddress=a.address,a.sealed_share_c&&this.opts.onShareC){const c=await rs(i,a.sealed_share_c,o);await this.opts.onShareC(c,a.address)}return this.walletData(a.address)}async getAddresses(e){const t=await this.requireWalletAddress(),r=await this.client.call("GET",`/wallets/${t}/addresses`);return((r==null?void 0:r.addresses)??[]).map(n=>({address:n.address,index:n.index,name:n.name||void 0}))}async getAddress(e,t){const r=await this.requireWalletAddress(),n=(await this.getAddresses(e)).find(a=>a.index===t);if(n)return{address:n.address,derivationPath:Yt(t)};const{result:i}=await this.withEnvelope("get_address",r,{command:"get_address",index:t},{pin:this.requirePin()},(a,o)=>this.client.call("PUT",`/wallets/${r}/addresses/${t}`,{envelope:a,intent:o}));return{address:i.address,derivationPath:Yt(t)}}async signMessage(e,t,r,n,i,a){const o=await this.resolveTarget(n,a),{result:c}=await this.withEnvelope("sign_message",o.address,{command:"sign_message",index:o.index,message:oe(Yi(r))},{pin:this.requirePin()},(u,f)=>this.client.call("POST",`/wallets/${o.address}/signatures`,{type:"message",envelope:u,intent:f}));return{chainId:t,signature:c.signature,format:"hex"}}async signTypedData(e,t,r,n,i,a){const o=await this.resolveTarget(n,a),c=typeof r=="string"?JSON.parse(r):r,{result:u}=await this.withEnvelope("sign_typed_data",o.address,{command:"sign_typed_data",index:o.index,typed_data:c},{pin:this.requirePin()},(f,g)=>this.client.call("POST",`/wallets/${o.address}/signatures`,{type:"typed_data",chain_id:t,envelope:f,intent:g}));return{chainId:t,signature:u.signature,format:"hex"}}async signTransaction(e,t,r,n){const i=await this.resolveTarget(n,r.from),{result:a}=await this.withEnvelope("sign",i.address,{command:"sign",index:i.index,unsigned_tx:ns(r,t)},{pin:this.requirePin()},(o,c)=>this.client.call("POST",`/wallets/${i.address}/signatures`,{type:"transaction",chain_id:t,envelope:o,intent:c}));return{chainId:t,signature:a.signed_tx,txHash:a.tx_hash,format:"hex"}}async sendTransaction(e,t,r){const n=await this.resolveTarget(void 0,r.from),{result:i}=await this.withEnvelope("sign",n.address,{command:"sign",index:n.index,unsigned_tx:ns(r,t)},{pin:this.requirePin()},(a,o)=>this.client.call("POST",`/wallets/${n.address}/transactions`,{chain_id:t,envelope:a,intent:o}));return{txHash:i.tx_hash}}async signOut(){this.walletAddress=null,await this.authzKeys.revoke()}walletData(e){return{id:e,address:e,derivationPath:Yt(0),createdAt:Date.now()}}async findWallet(){const e=await this.client.call("GET","/wallets"),t=Array.isArray(e)?e[0]??null:null;return this.walletAddress=(t==null?void 0:t.address)??null,t}async requireWalletAddress(){if(this.walletAddress)return this.walletAddress;const e=await this.findWallet();if(!e)throw new h(l.WALLET_NOT_FOUND,"no wallet for this account");return e.address}async resolveTarget(e,t){const r=await this.requireWalletAddress();if(!t&&!e)return{address:r,index:0};if(t&&t.toLowerCase()===r.toLowerCase()&&!e)return{address:r,index:0};const n=await this.getAddresses(""),i=t?n.find(a=>a.address.toLowerCase()===t.toLowerCase()):n.find(a=>a.index===e);if(!i)throw new h(l.TX_INVALID_PARAMS,t?`from is not an address of this wallet: ${t}`:`no derived address at index ${e}`);if(e!==void 0&&e!==i.index)throw new h(l.TX_INVALID_PARAMS,`from (index ${i.index}) does not match index ${e}`);return{address:i.address,index:i.index}}requirePin(){const e=this.opts.pinStore.get();if(!e)throw new h(l.PIN_NOT_SET,"PIN is required");return e}async withEnvelope(e,t,r,n,i){var a;for(let o=0;;o++){const c=await Mi({recipientPub:await this.client.getRecipientKey(),bindingId:t,command:e,intent:r,plaintext:n,authz:await this.authzKeys.get(),now:this.opts.now?new Date(this.opts.now()):void 0});try{return{result:await i(c.envelope,c.intent),aad:c.aad}}catch(u){if(o>0||!(u instanceof h))throw u;const f=(a=u.details)==null?void 0:a.serverCode;if(f==="AUTHZ_INVALID")this.authzKeys.invalidate();else if(f==="ENVELOPE_INVALID")this.client.forgetRecipientKey();else throw u}}}}const zi=3,Xi=/^0x(?:[0-9a-fA-F]{2}){4,}$/;function ji(s){return s.code===zi||/execution reverted/i.test(s.message??"")}class Zi{constructor(e,t){this.chainRegistry=e,this.transport=t,this._nextId=1}async call(e,t,r){const n=await this.chainRegistry.getChain(r),i={jsonrpc:"2.0",method:e,params:t,id:this._nextId++},o=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(o!=null&&o.error){const{code:c,message:u}=o.error,f={method:e,chainId:r,code:c,message:u,data:o.error.data},g=ji(o.error);throw g&&typeof f.data=="string"&&Xi.test(f.data)&&(f.revertData=f.data,f.selector=f.data.slice(0,10).toLowerCase()),new h(g?l.EXECUTION_REVERTED:l.UNKNOWN_ERROR,`RPC 오류 [${e}] (${r}): ${u} (코드: ${c})`,f)}return o==null?void 0:o.result}}class Qi{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){var r;(r=this.listeners.get(e))==null||r.delete(t)}emit(e,t){var r;(r=this.listeners.get(e))==null||r.forEach(n=>n(t))}removeAllListeners(){this.listeners.clear()}}function ea(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const t=new Uint8Array(16);return globalThis.crypto.getRandomValues(t),Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class he{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const t=Date.now();for(;Date.now()-t<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 he.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=he.getBridge(),!this.bridge)throw new h(l.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 h(l.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const t=await this.handshake();return this.context=t,d.log("[RNBridge] Bootstrap initialization complete",{activated:t.isActivated,ttl:`${t.absoluteTtlMs/1e3/60}min`}),t}async handshake(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=ea(),t=Date.now(),r={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:t,hmac:""};try{const n=await this.bridge.handshake(r);if(!n.activated)throw new h(l.AUTH_FAILED,"Bridge handshake rejected by native");const i=typeof n.walletName=="string"?n.walletName.trim():"",a=i.length>0&&i.length<=64?i:void 0,o=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:a,walletProvider:o}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new h(l.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFirebaseIdToken(),t=(e.expiresAt-Date.now())/1e3;if(t<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return this.touchActivity(),e}catch(e){if(e instanceof h)throw e;const t=e instanceof Error?e.message:String(e);throw t.includes("USER_REJECTED")||t.toLowerCase().includes("rejected")?new h(l.USER_REJECTED,"Firebase ID token request rejected by user",e):(d.error("[RNBridge] Firebase token request failed",e),new h(l.AUTH_FAILED,"Firebase token request failed",e))}}async requestFreshFirebaseIdToken(){if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");this.assertActive();try{const e=await this.bridge.requestFreshFirebaseIdToken();if((e.expiresAt-Date.now())/1e3<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return this.touchActivity(),e}catch(e){throw e instanceof h?e:(d.error("[RNBridge] Fresh Firebase token request failed",e),new h(l.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e))}}async requestFirebaseIdTokenForSessionRestore(){var e;if(!this.bridge)throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not initialized");if(!((e=this.context)!=null&&e.isActivated))throw new h(l.AUTH_NOT_INITIALIZED,"Bridge not activated");if(!this.bridge.requestFirebaseIdTokenForSessionRestore)throw new h(l.RN_NATIVE_SESSION_EXPIRED,"Native session restore bridge method is not available");try{const t=await this.bridge.requestFirebaseIdTokenForSessionRestore();if((t.expiresAt-Date.now())/1e3<60)throw new h(l.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return t}catch(t){throw t instanceof h?t:(d.warn("[RNBridge] Session restore Firebase token request failed",t),new h(l.RN_NATIVE_SESSION_EXPIRED,"Native bridge session restore failed. Please sign in again.",t))}}getContext(){return this.context}isActive(){var t;if(!((t=this.context)!=null&&t.isActivated))return!1;const e=Date.now();return!(e-this.context.activatedAt>this.context.absoluteTtlMs||e-this.context.lastActivityAt>this.context.idleTtlMs)}touchActivity(){this.context&&(this.context.lastActivityAt=Date.now())}assertActive(){if(!this.isActive())throw this.context=null,new h(l.SESSION_EXPIRED,"RN Bridge session expired. Please sign in again in the app.")}}var gt={environment:"production"};const Me={production:{oauthServiceUrl:"https://one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io",contentsBaseUrl:"https://contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"",oneWalletApiUrl:""},staging:{oauthServiceUrl:"https://stg-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://stg-oauth2.onechain.nexus",oneWalletApiUrl:""},development:{oauthServiceUrl:"https://dev-one-wallet-oauth.onechain.nexus",legacyOauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io",contentsBaseUrl:"https://stg-contents.crosstoken.io/frontend/common/app-launcher",oneIdIssuer:"https://dev-oauth2.onechain.nexus",oneWalletApiUrl:"https://dev-one-pocket-api.onechain.nexus/embed/v1"}};function ta(s){const e=s.environment,t=e&&e in Me?Me[e]:null;if(!t)return null;const r=s.overrides;if(!r)return t;const n={...t};for(const[i,a]of Object.entries(r))typeof a=="string"&&a.trim()!==""&&(n[i]=a);return n}function _t(){try{if(typeof gt<"u"){const s=typeof gt=="string"?JSON.parse(gt):gt,e=ta(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Me)return Me[s]}catch{}return Me.production}function as(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function ra(s,e=Dt){if(!s||s==="0x0"||s==="0x")return"0";try{const t=BigInt(s);if(t===0n)return"0";const r=10n**BigInt(Or),n=t/r,a=(t%r).toString().padStart(Or,"0"),o=as(a).slice(0,e);return o?`${n}.${o}`:`${n}`}catch{return"?"}}function pt(s,e,t,r=Dt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(t),a=n/i,c=(n%i).toString().padStart(t,"0"),u=as(c.slice(0,r)),f=u?`${a}.${u}`:`${a}`;return e?`${f} ${e}`:f}catch{return}}function sa(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Rr)throw new h(l.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Rr} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function na(s){const e=s.startsWith("0x")?s.slice(2):s;if(!/^[0-9a-fA-F]+$/.test(e))throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new h(l.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function ia(s,e){const t=aa(e);if(s==="0"){if(t!==void 0&&t!==0)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const r=s.match(/^eip155:(\d+)$/);if(r){const n=Number(r[1]);if(t===void 0)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${s})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==n)throw new h(l.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${s}, 예상값: ${n})와 일치하지 않습니다`)}}function aa(s){if(s==null||typeof s!="object")return;const e=s.domain;if(e==null||typeof e!="object")return;const t=e.chainId;if(t==null)return;const r=Number(t);return Number.isFinite(r)?r:void 0}const oa=new Set(["095ea7b3","a22cb465","39509351","d73dd623","87517c45"]),ca=new Set(["Permit","PermitSingle","PermitBatch","PermitTransferFrom","PermitBatchTransferFrom","PermitWitnessTransferFrom","PermitBatchWitnessTransferFrom"]);function la(s){var r;const{action:e,context:t}=s;if(e==="sign"||e==="send"){const n=(r=t.tx)==null?void 0:r.data;if(typeof n!="string")return!1;const i=n.trim().toLowerCase().replace(/^0x/,"");return i.length>=8&&oa.has(i.slice(0,8))}if(e==="sign-typed-data"){const n=da(t.typedData);return n===null||ca.has(n)}return!1}function da(s){let e=s;if(typeof e=="string")try{e=JSON.parse(e)}catch{return null}if(e&&typeof e=="object"&&"primaryType"in e){const t=e.primaryType;return typeof t=="string"?t:null}return null}function ha(s,e,t,r){if(!s)return!0;if(s.mode==="off"||e===null)return!1;const n=t-e;return n<0||n>=s.ttlMs?!1:!la(r)}function ua(s){return(s==null?void 0:s.mode)==="off"}class Fe{constructor(e){this.deps=e,this.verifyPinMutex=null}prepareForSigning(e){var r,n;if(!this.deps.pinStore.has())return;const t=(n=(r=this.deps).getPinReusePolicy)==null?void 0:n.call(r);ha(t,this.deps.pinStore.getSetAt(),Date.now(),e)||this.deps.pinStore.clear()}finishSigning(){var e,t;ua((t=(e=this.deps).getPinReusePolicy)==null?void 0:t.call(e))&&this.deps.pinStore.clear()}hasReusePolicy(){var e,t;return((t=(e=this.deps).getPinReusePolicy)==null?void 0:t.call(e))!==void 0}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new h(l.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.deps.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){var r,n;if((n=(r=this.deps).isRNBridgeMode)!=null&&n.call(r)||this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const t=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!t)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(t),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,t,r,n){var c,u;if((u=(c=this.deps).isRNBridgeMode)!=null&&u.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,a;this.verifyPinMutex=new Promise((f,g)=>{i=f,a=g});const o=we(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const g=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:t,attemptCount:r,maxAttempts:n});if(!g)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(g),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const f=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:t,attemptCount:r,maxAttempts:n,onSubmit:async g=>{this.deps.pinStore.set(g);try{return await this.deps.walletProvider.verifyPin(g)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:o.pin_input_error})}catch(S){if(this.deps.pinStore.clear(),S instanceof h){if(S.code===l.PIN_WRONG)return{ok:!1,error:o.pin_input_error};if(S.code===l.PIN_INVALID)return{ok:!1,error:S.message};if(S.code===l.PIN_LOCKED)return Fe.buildPinLockedResult(S,o)}throw S}}});if(!f)throw new h(l.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(f),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(f){if(f instanceof h&&(f.code===l.AUTH_NOT_AUTHENTICATED||f.code===l.AUTH_TOKEN_EXPIRED||f.code===l.SESSION_EXPIRED)&&f.code!==l.SESSION_EXPIRED){const g=we(this.deps.getLocale()??"en"),S=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:S?this.deps.maskEmail(S,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw a(f),f}throw a(f),f}finally{this.verifyPinMutex=null}}async withPinRetry(e){const t=we(this.deps.getLocale()??"en");let r=null;try{return await e()}catch(n){if(n instanceof h){if(r=Fe.parsePinError(n,t),!r)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",r.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(r.errorMessage,r.lockExpiresAt,r.attemptCount,r.maxAttempts);try{return await e()}catch(n){if(n instanceof h&&(r=Fe.parsePinError(n,t),r))continue;throw n}}}static parsePinError(e,t){if(e.code===l.PIN_WRONG)return{errorMessage:t.pin_input_error};if(e.code===l.PIN_INVALID)return{errorMessage:e.message};if(e.code===l.PIN_LOCKED){const r=e.details;return r!=null&&r.permanent?{errorMessage:t.pin_locked_permanent}:(r==null?void 0:r.remainingAttempts)!=null&&r.remainingAttempts>0&&r.maxAttempts?{errorMessage:t.pin_input_error,attemptCount:r.maxAttempts-r.remainingAttempts,maxAttempts:r.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:r==null?void 0:r.lockExpiresAt}}return null}static buildPinLockedResult(e,t){const r=Fe.parsePinError(e,t);if(!r)return{ok:!1,error:e.message};const{errorMessage:n,...i}=r;return{ok:!1,error:n,...i}}}class fa{constructor(e){this.deps=e,this.signingQueue=Promise.resolve()}async confirmAndExecuteWithPreparedPin(e){if(!this.deps.pinOrchestrator.hasReusePolicy())return this.confirmAndExecute(e);const t=this.signingQueue.then(()=>this.confirmAndExecute(e));return this.signingQueue=t.then(()=>{},()=>{}),t}async confirmAndExecute(e){var r,n;if((n=(r=this.deps).isRNBridgeMode)!=null&&n.call(r))return e.execute(void 0);if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new h(l.USER_REJECTED,e.rejectedMessage);this.deps.pinOrchestrator.prepareForSigning({action:e.prepareAction,context:e.prepareContext});try{return await 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)})}finally{this.deps.pinOrchestrator.finishSigning()}}}function ga(s){return s==="google"||s==="apple"}class _a{constructor(e){this.deps=e}async signInAgain(){var t,r;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=ga(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(u){throw this.deps.clearAuthState(),u}if(!i.success)return this.deps.clearAuthState(),i;const a=((t=i.user)==null?void 0:t.providerSub)??null,o=((r=i.user)==null?void 0:r.id)??null;if(!(e.providerSub?!!a&&a===e.providerSub:e.userId?!!o&&e.userId===o:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const u=we(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:u.session_alert_title,message:u.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,u.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(t){const r=we(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,r.session_alert_apple_account):void 0;if(t instanceof h&&t.code===l.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),t}if(t instanceof h&&t.code===l.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),t}if(!(t instanceof h)||t.code!==l.SESSION_EXPIRED)throw t;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:r.session_alert_title,message:r.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new h(l.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new h(l.SESSION_EXPIRED,o.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class pa{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,t,r){const n=this.deps.getUserId();if(!n)return;const i=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",i),i!=="exists")return;const a=await this.deps.walletProvider.getAddresses(n);if(a.length>0){let c,u=!1;if(t){const g=a.find(S=>S.address.toLowerCase()===t.toLowerCase());g?c=g:(c={address:t,index:0},u=!0)}else e!==void 0?c=a.find(g=>g.index===e)??a[0]:c=a[0];u?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",c.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address);const f=!!t&&!!r&&c.address.toLowerCase()===t.toLowerCase();this.deps.setActiveWallet(c.address,c.index,f?{walletName:r}:void 0);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(n,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class wa{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const t=this.deps.getAllowSkip(),r=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:t});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",r),r==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,a=5,o=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${a})`,n?`— 이전 메시지: ${n}`:"");const f=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:a});if(f===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 g=await((u=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:u.call(c,f,e));if(!g){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),o=f;break}if(g.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),o=f;break}const S=g.pinStatus;if(a=S.maxAttempts,i=a-S.remainingAttempts,S.remainingAttempts===0&&S.lockExpiresAt){const E=S.lockExpiresAt*1e3,m=Math.max(1,Math.round((E-Date.now())/1e3)),y=m<=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 잠금 — ${m}초, 메시지: ${y}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(m,y),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${a})`),n="Incorrect PIN."}catch(g){if(!(g instanceof h))throw g;if(g.code===l.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const S=we(this.deps.getLocale()??"en"),E=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:S.session_alert_title,message:S.alert_session_expired,email:E?this.deps.maskEmail(E,S.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(),g}if(g.code===l.MIGRATION_PIN_LOCKED){const S=g.details;if(a=(S==null?void 0:S.maxAttempts)??5,(S==null?void 0:S.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 E=((S==null?void 0:S.lockExpiresAt)??0)*1e3,m=Math.max(1,Math.round((E-Date.now())/1e3)),y=m<=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 이미 잠금 — ${m}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(m,y),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",g),g}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const f=await this.deps.executeMigrate(o,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof h&&f.code===l.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof h&&f.code===l.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const g=we(this.deps.getLocale()??"en"),S=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:S?this.deps.maskEmail(S,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const y=await this.deps.executeMigrate(o,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",y.address),y}catch(y){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",y),y}}throw this.deps.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}}class Sa{constructor(e){this.deps=e}async withResolvedGasAndFee(e,t){const r=E=>!(E!=null&&E.trim()),n=e.nonce===void 0||e.nonce===null,i=r(e.gasLimit),a=r(e.gasPrice)&&r(e.maxFeePerGas),o=!r(e.maxFeePerGas)&&r(e.maxPriorityFeePerGas);if(!n&&!i&&!a&&!o)return e;const c={...e},u=n?c.from??this.deps.getActiveAddress()??void 0:void 0;u&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",u,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),a&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[f,g,S]=await Promise.all([u?this.deps.jsonRpcCall("eth_getTransactionCount",[u,"pending"],t):null,i?this.deps.estimateGas(e,t):null,a?this.deps.getBaseFeePerGas(t):null]);if(u&&(c.nonce=parseInt(f??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=g,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),a){const E=S;if(E){const m=Tr;c.maxFeePerGas=`0x${(BigInt(E)+BigInt(m)).toString(16)}`,c.maxPriorityFeePerGas=m,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",E,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Un,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!a&&o&&(c.maxPriorityFeePerGas=Tr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ea{constructor(e){this.crypto=e}verifySignatureSigner(e,t,r){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,t);if(n.toLowerCase()!==r.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:r,recovered:n}),new h(l.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${r}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof h)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function ma(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class ya{constructor(e){this.deps=e}setActiveWallet(e,t,r){this.deps.setState({address:e,activeWalletIndex:t});const n={address:e,index:t};(r==null?void 0:r.walletName)!==void 0&&(n.walletName=r.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:t,address:e}).catch(()=>{})}applyAuthResult(e,t){var n,i,a,o,c;const r={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:((a=e.user)==null?void 0:a.providerSub)??null,loginType:ma((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((c=e.user)==null?void 0:c.id)??null,...t?{source:t}:{}})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Aa{constructor(e){this.deps=e}async resolveAddress(e){const t=this.deps.getActiveWalletIndex(),r=this.deps.getActiveAddress();if(e===void 0||e===t){if(!r&&this.deps.ensureWallet)return{address:await this.deps.ensureWallet(),index:t};if(!r)throw new h(l.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:r,index:t}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class Ia{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new h(l.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new h(l.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Ta{constructor(e){this.deps=e}async createWallet(){var n,i;const e=this.deps.getUserId();if(!e)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const t=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",t),t==="migration_required"){const a=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",a);const o=await this.deps.migrationOrchestrator.handleMigrationFlow(a);if(o)return this.deps.setActiveWallet(o.address,0),{address:o.address};throw new h(l.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(t==="exists")return await this.deps.pinOrchestrator.ensureVerifiedPin(),{address:(await this.tryGetOrCreateWalletWithMigrationFallback(e)).address};await this.deps.pinOrchestrator.ensurePinSetup();const r=await this.tryGetOrCreateWalletWithMigrationFallback(e);return r.migrated||await((i=(n=this.deps).showWalletCreated)==null?void 0:i.call(n)),{address:r.address}}async tryGetOrCreateWalletWithMigrationFallback(e){try{const t=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(t.address,0),d.log("[CROSSx] 지갑 준비 완료:",t.address),{address:t.address,migrated:!1}}catch(t){if(t instanceof h&&t.code===l.MIGRATION_BACKUP_EXISTS){const r=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(r);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address,migrated:!0};throw new h(l.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw t}}}function os(s,e){const t=s.replace(/\/$/,""),r=e.startsWith("/")?e:`/${e}`;return`${t}/cross-auth${r}`}class Ra{constructor(e){this.deps=e}async registerTokenHistory(e,t,r){if(!(e!=null&&e.trim()))throw new h(l.TX_INVALID_PARAMS,"invalid param chain_id");if(!(t!=null&&t.trim()))throw new h(l.TX_INVALID_PARAMS,"invalid param tx_hash");const n=t.startsWith("0x")?t:`0x${t}`;if(!/^0x[0-9a-fA-F]{64}$/.test(n))throw new h(l.TX_INVALID_PARAMS,"invalid param tx_hash");if(!(r!=null&&r.trim())||r.length>64)throw new h(l.TX_INVALID_PARAMS,"invalid param body");const i=this.deps.getApiBaseUrl(),a=os(i,`/v2/token-historical/${e}/${n}`),o={clientVersion:r};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:a,method:"POST",headers:{"Content-Type":"application/json"},body:o,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof h?c:new h(l.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const t=this.deps.getApiBaseUrl(),r=new URL(os(t,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&r.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&r.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:r.toString(),method:"GET",retries:0});if(i.status===404)throw new h(l.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 h?i:new h(l.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,t,r,n){const i=(n==null?void 0:n.maxRetries)??3,a=(n==null?void 0:n.retryDelayMs)??2e3;for(let o=0;o<i;o++)try{await this.registerTokenHistory(e,t,r);return}catch(c){if(c instanceof h&&c.message.includes("404")&&o<i-1){d.log(`[TokenHistory] Retry ${o+1}/${i} (404 - tx not yet indexed)`),await new Promise(f=>setTimeout(f,a));continue}throw c}}handleError(e,t){const n={400:{code:l.TX_INVALID_PARAMS,message:`Bad request (400): ${t==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:l.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:l.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:l.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new h(n.code,n.message)}}function zt(s,e="Apple account"){if(s.endsWith("@privaterelay.appleid.com"))return e;const t=s.indexOf("@");if(t<0)return"*".repeat(s.length||3);const r=s.substring(0,t),n=s.substring(t);return r.length<=1?`${r}${"*".repeat(Math.max(r.length,1))}${n}`:`${r[0]}${"*".repeat(r.length-1)}${n}`}const Ie=class Ie extends Qi{constructor(e,t,r,n,i,a,o,c,u,f,g,S,E){var m,y;super(),this.storage=r,this.crypto=n,this.transport=i,this.oauth=a,this.walletProvider=o,this.tokenStore=c,this.pinEncryptor=S,this.oneIdAuth=E,this._warnedUnknownNativeCurrency=new Set,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._bridgeSessionRestorePromise=null,this._sdkDeprecationNotified=!1,this._sdkUnsupportedNotified=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=t,e.logger&&Dr(e.logger),this.confirmation=u,this.pinStore=g??new Mt,this.stateManager=new ya({setState:w=>{w.authenticated!==void 0&&(this.authenticated=w.authenticated),w.userId!==void 0&&(this.userId=w.userId),w.address!==void 0&&(this.address=w.address),w.activeWalletIndex!==void 0&&(this.activeWalletIndex=w.activeWalletIndex),w.userEmail!==void 0&&(this.userEmail=w.userEmail),w.providerSub!==void 0&&(this.providerSub=w.providerSub),w.loginType!==void 0&&(this.loginType=w.loginType),w.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=w.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:w,index:A,walletName:P})=>{const F={address:w,index:A};P!==void 0&&(F.walletName=P),this.emit("addressChanged",F)},emitAuthChanged:({isAuthenticated:w,address:A,userId:P,source:F})=>{this.emit("authChanged",{isAuthenticated:w,address:A,userId:P,...F?{source:F}:{}})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Ie.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Fe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:zt,signInAgain:()=>this.signInAgain(),isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge,getPinReusePolicy:()=>this.internalConfig.pinReuse}),this.signingOrchestrator=new fa({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new pa({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(w,A,P)=>this.setActiveWallet(w,A,P)}),this.migrationOrchestrator=new wa({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(w,A)=>this.migrateWalletUseCase.execute(w,A),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:zt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var w;return((w=this._config.migration)==null?void 0:w.allowSkip)??!0}}),this.transactionLifecycleService=new Sa({getActiveAddress:()=>this.address,estimateGas:(w,A)=>this.estimateGas(w,A),getBaseFeePerGas:w=>this.getBaseFeePerGas(w),jsonRpcCall:(w,A,P)=>this.jsonRpc.call(w,A,P)}),this.signatureVerifier=new Ea(this.crypto),this.addressResolverService=new Aa({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId,ensureWallet:this.usesOneWallet?()=>this.walletCreationService.createWallet().then(w=>w.address):void 0}),this.authGuardService=new Ia({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Ta({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(w,A)=>this.setActiveWallet(w,A),showWalletCreated:()=>{var w,A;return((A=(w=this.confirmation).showWalletCreatedPrompt)==null?void 0:A.call(w))??Promise.resolve()}}),this.tokenHistoryService=new Ra({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new _a({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:w=>{this._isRecoveringSession=w},setAuthenticated:w=>{this.authenticated=w},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:w=>this.signInUseCase.execute(w),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:w=>this.confirmation.showSessionAlert(w),clearAuthState:()=>this.clearAuthState(),applyAuthResult:w=>this.applyAuthResult(w),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:zt}),this.chainRegistry=f,this.jsonRpc=new Zi(f,i),this.signInUseCase=new Bt(this.internalConfig,r,n,a,i,o,c,void 0,()=>this._config.locale),this.signOutUseCase=new ti(this.internalConfig,r,c,this._config.persistWalletPreference!==!1?[Ie.WALLET_PREF_KEY]:[]),this.migrateWalletUseCase=new ri(r,o),(m=o.setOnUnauthorized)==null||m.call(o,()=>this.forceLogout()),(y=o.setTokenRefresher)==null||y.call(o,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}handleSdkVersionDeprecation(e){if(this._sdkDeprecationNotified)return;this._sdkDeprecationNotified=!0;const t=ot;console.warn(`[CROSSx] ${t} is deprecated`+(e.sunset?` and will stop working on ${e.sunset}`:"")+". Update @nexus-cross/crossx-sdk-core."+(e.infoUrl?` See ${e.infoUrl}`:"")),this.emit("versionDeprecated",{version:t,sunset:e.sunset,infoUrl:e.infoUrl})}handleSdkVersionUnsupported(e){this._sdkUnsupportedNotified||(this._sdkUnsupportedNotified=!0,console.error(`[CROSSx] ${ot} is no longer supported by the wallet gateway. Update @nexus-cross/crossx-sdk-core.`+(e.message?` (${e.message})`:"")),this.confirmation.showUpdateRequired().catch(t=>{d.warn("[CROSSx] 업데이트 필요 모달 표시 실패:",t)}))}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}async clearRNBridgeDelegation(e){if(this._isAuthenticatedViaRNBridge){this._isAuthenticatedViaRNBridge=!1,d.info("[CROSSx] RN Bridge native sign delegation 해제 —",e);try{await this.signInUseCase.clearStoredRNBridgeSession()}catch(t){d.warn("[CROSSx] 저장된 bridge 세션 마커 제거 실패",t)}}}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 t,r;d.log("[CROSSx SDK] v3.0.0-beta.1 초기화 중..."),this.confirmation.setMessages(we(this._config.locale));try{const n=_t();if(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,(r=(t=this.crypto).setJWKSEndpoint)==null||r.call(t,`${n.authApiUrl}/.well-known/jwks.json`),this.usesOneWallet){const u=await this.restoreOneWalletSession();return this.initialized=!0,d.info("[CROSSx SDK] v3.0.0-beta.1 초기화 완료 (one-wallet)"),this.emit("initialized",{restored:!!(u!=null&&u.success)}),u}const i=this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,a=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let o=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((o==null?void 0:o.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),o=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success){this.applyAuthResult(c);const u=this.address&&(!o||this.address.toLowerCase()===o.toLowerCase()),f=this._rnBridgeWalletName&&o&&this._rnBridgeWalletAddress&&o.toLowerCase()===this._rnBridgeWalletAddress.toLowerCase()?this._rnBridgeWalletName:void 0;if(u)this.address&&this.setActiveWallet(this.address,a??this.activeWalletIndex,f?{walletName:f}:void 0);else try{await this.loadWalletAfterAuth(a,o,f)}catch(g){if(g instanceof h&&g.code===l.PIN_CANCELLED)d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속");else if(g instanceof h&&(g.code===l.SESSION_EXPIRED||g.code===l.AUTH_NOT_AUTHENTICATED||g.code===l.USER_NOT_FOUND))d.warn("[CROSSx] initialize: 복원된 세션이 유효하지 않음 — 세션 정리 후 비로그인으로 계속",g.code),this.clearAuthState(),await this.signOutUseCase.execute().catch(()=>{}),c=null;else throw g}}return this.initialized=!0,d.info("[CROSSx SDK] v3.0.0-beta.1 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new h(l.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!he.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:"3.0.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId});const e=new he({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"3.0.0-beta.1",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),t=await e.initialize();this._rnBridgeService=e,this._rnBridgeWalletAddress=t.walletAddress,this._rnBridgeWalletName=t.walletName,this._rnBridgeWalletProvider=t.walletProvider,this.subscribeBridgeWalletChanged(),d.info("[CROSSx] RN Bridge Handshake 성공",{walletAddress:t.walletAddress??"(없음)",walletName:t.walletName??"(없음)"});const r=await this.signInUseCase.hasStoredRNBridgeSession();if(r&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 마커 감지 — native sign delegation 활성")),await this.signInUseCase.hasValidStoredAccessToken())return null;if(r){const n=await this._tryBridgeSessionRestore();if(n!=null&&n.success)return n}return d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null}catch(e){return d.info("[CROSSx][RNBridge trace] Bootstrap failed detail",{name:e instanceof Error?e.name:typeof e,message:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,cause:e instanceof Error?e.cause:void 0}),d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;if(!this._rnBridgeService.isActive()){const t=this._rnBridgeService.getContext(),r=Date.now();d.info("[CROSSx] Bridge 세션 만료 감지 — 재핸드셰이크 시도",{elapsedSinceActivatedMs:t?r-t.activatedAt:"(context 없음)",idleMs:t?r-t.lastActivityAt:"(context 없음)",absoluteTtlMs:(t==null?void 0:t.absoluteTtlMs)??"(context 없음)",idleTtlMs:(t==null?void 0:t.idleTtlMs)??"(context 없음)",absoluteExpired:t?r-t.activatedAt>t.absoluteTtlMs:"(context 없음)",idleExpired:t?r-t.lastActivityAt>t.idleTtlMs:"(context 없음)"});try{const n=Date.now(),i=await this._rnBridgeService.initialize();this._rnBridgeWalletAddress=i.walletAddress,this._rnBridgeWalletName=i.walletName,this._rnBridgeWalletProvider=i.walletProvider,d.info("[CROSSx] Bridge 재핸드셰이크 성공 — bridge 로그인 계속 진행",{tookMs:Date.now()-n,walletAddress:i.walletAddress??"(없음)",walletName:i.walletName??"(없음)",absoluteTtlMs:i.absoluteTtlMs,idleTtlMs:i.idleTtlMs})}catch(n){return d.warn("[CROSSx] Bridge 재핸드셰이크 실패 — bridge 비활성화 후 OAuth fallback",n),this._rnBridgeService=null,null}}try{const t=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const r=await this.signInUseCase.executeWithNativeFirebaseIdToken(t);return r.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(r),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress,this._rnBridgeWalletName),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=r.user)==null?void 0:e.id}),r):null}catch(t){return t instanceof h&&t.code===l.USER_REJECTED?(await this.clearRNBridgeDelegation("사용자가 자동 로그인을 취소"),d.log("[CROSSx] Bridge 로그인 거부 — OAuth fallback 진행 (bridge 유지)"),null):t instanceof h&&t.code===l.SESSION_EXPIRED?(d.warn("[CROSSx] Bridge 세션 만료 — OAuth fallback 진행"),null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패",t),!1)}}async _tryBridgeSessionRestore(){return this._rnBridgeService?this._bridgeSessionRestorePromise?this._bridgeSessionRestorePromise:(this._bridgeSessionRestorePromise=(async()=>{var e;try{if(!await this.signInUseCase.hasStoredRNBridgeSession())return null;if(await this.signInUseCase.hasValidStoredAccessToken())return this._isAuthenticatedViaRNBridge=!0,null;d.log("[CROSSx] RN Bridge 세션 복원 시도 — native Connect 승인 이력 확인");const t=await this._rnBridgeService.requestFirebaseIdTokenForSessionRestore(),r=await this.signInUseCase.executeWithNativeFirebaseIdToken(t);return r.success?(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] RN Bridge 세션 복원 성공",{userId:(e=r.user)==null?void 0:e.id}),r):(this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 실패:",r.error),null)}catch(t){return this._isAuthenticatedViaRNBridge=!1,d.warn("[CROSSx] RN Bridge 세션 복원 불가 — 비로그인 상태 유지",t),null}finally{this._bridgeSessionRestorePromise=null}})(),this._bridgeSessionRestorePromise):null}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new h(l.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 h(l.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return he.getBridge()}async signIn(e){if(this.ensureInitialized(),this.ensureNotOneWallet("signIn"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");const t=!!(e!=null&&e.provider)&&!!this._rnBridgeWalletProvider&&e.provider!==this._rnBridgeWalletProvider;if(t&&d.log(`[CROSSx] 선택한 provider(${e==null?void 0:e.provider})가 bridge 연결 provider(${this._rnBridgeWalletProvider})와 불일치 — bridge 건너뛰고 OAuth 진행`),this._rnBridgeService&&!t){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 r=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 h(l.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:n.provider}}try{const n=await this.signInUseCase.execute(r);return n.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(n)),n}catch(n){throw n instanceof h?n:new h(l.AUTH_FAILED,"로그인에 실패했습니다",n)}}async signInWithCreate(e){const{preferredWalletAddress:t,...r}=e??{},n=await this.signIn(r);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:o}=await this.createWallet(),c=await this.getAddresses(),u=await this.selectWalletIfMultiple(c,t);return{...n,address:(u==null?void 0:u.address)??o,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i,t);return{...n,address:(a==null?void 0:a.address)??n.address,addresses:i}}catch(i){throw i instanceof h&&(i.code===l.PIN_CANCELLED||i.code===l.UI_NOT_PROVIDED)&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 또는 화면 없음 — 자동 로그아웃 진행"),await this.signOut().catch(a=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",a))),i}}async signInWithOAuthToken(e){var r,n;if(this.ensureInitialized(),this.ensureNotOneWallet("signInWithOAuthToken"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let t;try{t=await this.signInUseCase.executeWithOAuthToken(e),t.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(t,"external"),(n=(r=this.oauth).cancelPending)==null||n.call(r,"signInWithOAuthToken으로 외부 인증이 도착했습니다"))}catch(i){throw i instanceof h?i:new h(l.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",i)}if(!t.success)return{...t,addresses:[]};try{if(t.needsMigration||!t.address){const{address:o}=await this.createWallet(),c=await this.getAddresses(),u=await this.selectWalletIfMultiple(c);return{...t,address:(u==null?void 0:u.address)??o,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...t,address:(a==null?void 0:a.address)??t.address,addresses:i}}catch(i){throw i instanceof h&&(i.code===l.PIN_CANCELLED||i.code===l.UI_NOT_PROVIDED)&&(d.log("[CROSSx] signInWithOAuthToken: 비밀번호 설정 취소 또는 화면 없음 — 자동 로그아웃 진행"),await this.signOut().catch(a=>d.warn("[CROSSx] signInWithOAuthToken: 자동 로그아웃 실패",a))),i}}async signInWithJWT(e,t){if(this.ensureInitialized(),this.ensureNotOneWallet("signInWithJWT"),this.authenticated)throw new h(l.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithJWT(e,t);return r.success&&(this._isAuthenticatedViaRNBridge=!1,this.applyAuthResult(r)),r}catch(r){throw r instanceof h?r:new h(l.AUTH_FAILED,"JWT 로그인에 실패했습니다",r)}}signInWithOneId(e){var a,o;let t;try{t=this.oneIdContext()}catch(c){return Promise.reject(c)}const{port:r,config:n,sessions:i}=t;return r.authorize({...n,mode:(e==null?void 0:e.mode)??((a=this._config.oneId)==null?void 0:a.mode)??"auto",redirectUri:(o=this._config.oneId)==null?void 0:o.redirectUri,returnTo:e==null?void 0:e.returnTo}).then(async c=>{if(c.status==="redirecting")return c;const u=i.save(c.tokens);return this.usesOneWallet&&await this.applyOneIdSession(u),{status:"signed-in",session:u,returnTo:c.returnTo}})}async completeOneIdSignIn(e=window.location.href){const{port:t,config:r,sessions:n}=this.oneIdContext(),{tokens:i,returnTo:a}=await t.completeRedirect(r,e),o=n.save(i);return this.usesOneWallet&&await this.applyOneIdSession(o),{session:o,returnTo:a}}async getOneIdSession(){return this.oneIdContext().sessions.get()}async getOneIdAccessToken(){const e=this.usesOneWallet&&this._initPromise?this.oneIdContextUnchecked():this.oneIdContext();try{return await e.sessions.getAccessToken()}catch(t){throw this.usesOneWallet&&Vr(t)&&this.clearAuthState(),t}}async signOutOneId(){const{sessions:e}=this.oneIdContext();this.walletProvider instanceof is&&await this.walletProvider.signOut().catch(t=>d.warn("[CROSSx] B 키 폐기 실패 (로그아웃은 진행)",t));try{await e.signOut()}finally{this.usesOneWallet&&this.clearAuthState()}}ensureNotOneWallet(e){if(this.usesOneWallet)throw new h(l.NOT_IMPLEMENTED,`walletServer 'one-wallet' 에서는 ${e}() 를 쓸 수 없습니다. signInWithOneId() 로 로그인하세요`)}get usesOneWallet(){return this._config.walletServer==="one-wallet"}async restoreOneWalletSession(){await this.signOutUseCase.hasStoredSession().catch(()=>!1)&&(d.log("[CROSSx] one-wallet: 저장된 2.x 로그인 토큰을 무시하고 지운다"),await this.signOutUseCase.execute().catch(t=>d.warn("[CROSSx] 2.x 토큰 정리 실패",t)));let e;try{e=await this.oneIdContextUnchecked().sessions.get()}catch(t){return d.warn("[CROSSx] one-wallet: ONE ID 세션 복원 실패 — 로그아웃 상태로 시작",t),null}return e?this.applyOneIdSession(e):null}async applyOneIdSession(e){var n,i;let t;try{await((i=(n=this.walletProvider).checkWallet)==null?void 0:i.call(n))==="exists"&&(t=(await this.walletProvider.getOrCreateWallet(e.subject)).address)}catch(a){if(Vr(a))throw a;d.warn("[CROSSx] one-wallet: 지갑 조회 실패 — 주소 없이 로그인 상태로 둔다",a)}const r={success:!0,address:t,user:{id:e.subject}};return this.applyAuthResult(r),t&&this.setActiveWallet(t,0),r}oneIdContext(){return this.ensureInitialized(),this.oneIdContextUnchecked()}oneIdContextUnchecked(){const e=this._config.oneId;if(!this.oneIdAuth||!(e!=null&&e.clientId))throw new h(l.NOT_IMPLEMENTED,"이 환경에서는 ONE ID 로그인을 사용할 수 없습니다 (SDKConfig.oneId 필요)");const t=e.issuer||_t().oneIdIssuer;if(!t)throw new h(l.NOT_IMPLEMENTED,"ONE ID issuer가 정해지지 않았습니다. SDKConfig.oneId.issuer를 지정하세요");const r={issuer:t,clientId:e.clientId,scope:e.scope};return this._oneIdSessions??(this._oneIdSessions=new _i(this.oneIdAuth,r,pi(e.storage))),{port:this.oneIdAuth,config:r,sessions:this._oneIdSessions}}async signOut(){if(this.ensureInitialized(),this.usesOneWallet){await this.signOutOneId();return}try{await this.signOutUseCase.execute(),this.clearAuthState();const e=he.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(t){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",t)}}catch(e){throw new h(l.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(r){r instanceof h&&r.code===l.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: bridge loadWalletAfterAuth 실패:",r)}return!0}const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0),this.applyAuthResult(t);try{await this.loadWalletAfterAuth()}catch(r){r instanceof h&&r.code===l.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const t=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(t.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",t.address),t}catch(t){throw t instanceof h?t:new h(l.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",t)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new h(l.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,t){if(this.ensureAuthenticated(),!this.userId)throw new h(l.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 n=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const i=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,i)))).address,index:i};return r.push(o),o},e,t);return n&&this.setActiveWallet(n.address,n.index),n}async selectWalletIfMultiple(e,t){if(e.length<2)return null;const r=this._isAuthenticatedViaRNBridge?this._rnBridgeWalletAddress??this.address??void 0:void 0,n=!r&&this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,i=r?[r,t]:[t,n==null?void 0:n.address];for(const a of i){if(typeof a!="string"||!a)continue;const o=e.find(c=>c.address.toLowerCase()===a.toLowerCase());if(o)return this.setActiveWallet(o.address,o.index),o}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof h?e:new h(l.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(t){throw t instanceof h?t:new h(l.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,t)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),t=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};t(e.matches);const r=n=>t(n.matches);e.addEventListener("change",r),this._themeMediaCleanup=()=>e.removeEventListener("change",r)}applyTheme(e=this._config.theme??"light",t=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:t}),this.confirmation.setTheme(e,t)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(we(e))}setPinKeyboard(e){var t,r;this._config=Object.freeze({...this._config,pinKeyboard:e}),(r=(t=this.confirmation).setPinKeyboard)==null||r.call(t,e)}resolveNativeCurrency(e){const t=Zn(e,this._config.nativeCurrencies);return t||(this._warnedUnknownNativeCurrency.has(e)||(this._warnedUnknownNativeCurrency.add(e),console.warn(`[CROSSx SDK] ${e} 의 native 통화 정보가 없어 심볼을 비우고 decimals 를 18 로 가정합니다. 컨펌 모달 금액이 단위 없이 표시되며, decimals 가 18 이 아니면 금액이 틀립니다. SDKConfig.nativeCurrencies 에 { '${e}': { symbol, decimals } } 를 넘겨 주세요.`)),jn)}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,t,r){return this.withSessionRecovery(()=>this._signMessage(e,t,r))}async _signMessage(e,t,r){const n=he.getBridge(),i=this._isAuthenticatedViaRNBridge||!this.authenticated;if(n!=null&&n.signMessage&&i)try{const o=await n.signMessage({chainId:e,message:t,from:this.address??"",index:(r==null?void 0:r.index)??0,dappName:(r==null?void 0:r.dappName)??this._config.appName});return{chainId:e,signature:o.signature,message:t,address:this.address??""}}catch(o){if(!vr(o))throw Ue(o,l.SIGNATURE_FAILED);await this.clearRNBridgeDelegation("native signMessage 가 ERR_BRIDGE_NOT_AUTHORIZED 로 거부"),d.warn("[CROSSx] Bridge 미인증 — 일반 서명 경로로 폴백 (signMessage)")}if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const a=await this.resolveAddress(r==null?void 0:r.index);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:a.address,message:t,dappName:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:t,from:a.address},execute:c=>this.walletProvider.signMessage(this.userId,e,t,r==null?void 0:r.index,c,a.address)});return this.signatureVerifier.verifySignatureSigner(t,o.signature,a.address),{chainId:e,signature:o.signature,message:t,address:a.address}}catch(o){throw o instanceof h?o:new h(l.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,t,r){return this.withSessionRecovery(()=>this._signTypedData(e,t,r))}async _signTypedData(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new h(l.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ia(e,t);const n=await this.resolveAddress(r==null?void 0:r.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-typed-data",chainId:e,from:n.address,typedData:t,dappName:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the typed data signing request",prepareAction:"sign-typed-data",prepareContext:{typedData:t,from:n.address},execute:a=>this.walletProvider.signTypedData(this.userId,e,t,r==null?void 0:r.index,a,n.address)});return sa(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof h?i:new h(l.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,t){return this.signTypedData(Ie.OFFCHAIN_CHAIN_ID,e,t)}async signTransaction(e,t,r){return this.withSessionRecovery(()=>this._signTransaction(e,t,r))}async _signTransaction(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(t,e);n.from||(n.from=(await this.resolveAddress(r==null?void 0:r.index)).address);const i=this.resolveNativeCurrency(e);try{const a=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:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the transaction signing request",prepareAction:"sign",prepareContext:{tx:n},execute:o=>this.walletProvider.signTransaction(this.userId,e,n,r==null?void 0:r.index,o)});return na(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof h)throw a;const o=a instanceof Error?a.message:String(a);throw new h(l.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${o}`,a)}}async sendTransaction(e,t,r){return this.withSessionRecovery(()=>this._sendTransaction(e,t,r))}async _sendTransaction(e,t,r){if(this.ensureAuthenticated(),!this.userId)throw new h(l.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(t,e);n.from||(n.from=(await this.resolveAddress(r==null?void 0:r.index)).address);const i=this.resolveNativeCurrency(e);try{const a=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:(r==null?void 0:r.dappName)??this._config.appName,accountName:r==null?void 0:r.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async f=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,f)).txHash;const g=await this.walletProvider.signTransaction(this.userId,e,n,r==null?void 0:r.index,f);return g.txHash??g.signature}}),o=(t.data??"").toLowerCase().replace(/^0x/,""),c=o===""||o==="00000000",u=o.startsWith("a9059cbb");return(c||u)&&this.tokenHistoryService.registerHistoryFireAndForget(e,a,ot).catch(f=>d.log("[TokenHistory] register failed (non-critical):",f)),{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof h)throw a;const o=a instanceof Error?a.message:String(a);throw new h(l.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${o}`,a)}}async getTransactionReceipt(e,t){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],t)??null}catch{return null}}async waitForTxAndGetReceipt(e,t,r={}){const n=r.intervalMs??kn,i=Ln,a=r.timeoutMs??Ir,o=Date.now()+a;let c=n;for(;Date.now()<o;){const u=await this.getTransactionReceipt(e,t);if(u)return u;await new Promise(f=>setTimeout(f,c)),c=Math.min(c*2,i)}throw new h(l.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,t,r={}){var y,w;if(this._isAuthenticatedViaRNBridge){const A=he.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,t,r)}const{intervalMs:n,timeoutMs:i,...a}=r,{txHash:o}=await this.sendTransaction(e,t,a),c=n??((y=this._config.receiptPolling)==null?void 0:y.intervalMs)??Dn,u=i??((w=this._config.receiptPolling)==null?void 0:w.timeoutMs)??Ir,f=this.resolveNativeCurrency(e),g=t.from??"";let S,E;const m=this.waitForTxAndGetReceipt(o,e,{intervalMs:c,timeoutMs:u}).then(A=>{S=A;const P=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),F=t.value?BigInt(t.value):0n,M=pt(t.value,f.symbol,f.decimals,this._config.displayDecimals),V=pt("0x"+P.toString(16),f.symbol,f.decimals,this._config.displayDecimals),U=pt("0x"+(F+P).toString(16),f.symbol,f.decimals,this._config.displayDecimals);return{chainId:e,txHash:o,from:A.from,to:A.to??t.to,amount:M,fees:V,total:U,nativeSymbol:f.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(E=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:o,from:g,to:t.to,amount:pt(t.value,f.symbol,f.decimals,this._config.displayDecimals),nativeSymbol:f.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:o,from:g,to:t.to},m),E)throw E;return{chainId:e,txHash:o,receipt:S}}async bridgeSendTransactionWithWaitForReceipt(e,t,r,n){let i;try{i=await e.sendTransactionWithWaitForReceipt({chainId:t,tx:{to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nonce:r.nonce},from:r.from,dappName:n.dappName??this._config.appName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs})}catch(a){throw Ue(a,l.TRANSACTION_FAILED)}return{chainId:t,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??r.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,t){this.ensureAuthenticated();const r=this.walletProvider;if(typeof r.changePin!="function")throw new h(l.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await r.changePin(e,t),this.pinStore.set(t),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof h?n:new h(l.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${r}`,t)}}async estimateGas(e,t){this.ensureAuthenticated();const r={};e.from&&(r.from=e.from),e.to&&(r.to=e.to),e.value&&(r.value=e.value),e.data&&(r.data=e.data),e.gasPrice&&(r.gasPrice=e.gasPrice),e.maxFeePerGas&&(r.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(r.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(r.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[r],t)}catch(n){if(n instanceof h&&n.code===l.EXECUTION_REVERTED)throw n;const i=n instanceof Error?n.message:String(n);throw new h(l.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${t}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const t=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(t==null?void 0:t.baseFeePerGas)??null}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${r}`,t)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(t){const r=t instanceof Error?t.message:String(t);throw new h(l.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${r}`,t)}}async getNonce(e){this.ensureAuthenticated();const t=this.address;if(!t)return 0;try{const r=await this.jsonRpc.call("eth_getTransactionCount",[t,"pending"],e);return parseInt(r??"0x0",16)}catch(r){if(r instanceof h)throw r;const n=r instanceof Error?r.message:String(r);throw new h(l.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,r)}}async getBalance(e){this.ensureAuthenticated();const t=this.address;if(!t)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[t,"latest"],e)??"0x0";return{wei:n,formatted:ra(n,this._config.displayDecimals),chainId:e}}catch(r){if(r instanceof h)throw r;const n=r instanceof Error?r.message:String(r);throw new h(l.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,r)}}getProvider(e){this.ensureAuthenticated();let t=this._providers.get(e);return t||(t=new Ut(this,e),this._providers.set(e,t)),t}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(t=>{try{t.emit("accountsChanged",[e])}catch(r){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",r)}})}async walletRpc(e,t,r){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,t,r)}catch(n){if(n instanceof h)throw n;const i=n instanceof Error?n.message:String(n);throw new h(l.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${r}): ${i}`,n)}}setActiveWallet(e,t,r){const n=this.address;this.stateManager.setActiveWallet(e,t,r),n&&e&&n.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=he.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",t=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!t||typeof t!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",t);return}const r=t,n=typeof r.address=="string"?r.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",r);return}if(r.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",r);return}if(!this.authenticated&&!this._isAuthenticatedViaRNBridge){d.warn("[walletChanged] not authenticated — 이벤트 무시",r);return}const i=typeof r.walletName=="string"?r.walletName.trim():"",a=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:r.walletId,source:r.source,walletName:a}),this.setActiveWallet(n,0,{walletName:a}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=a)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e,t){this.stateManager.applyAuthResult(e,t)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.ensureNotOneWallet("signInAgain"),this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.usesOneWallet?e():this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,t,r){return this.walletLifecycleService.loadWalletAfterAuth(e,t,r)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,t,r){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,t,r))}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(),Dr(null)}};Ie.WALLET_PREF_KEY="wallet_preference",Ie.OFFCHAIN_CHAIN_ID="0";let Ze=Ie;class Oa{constructor(){this.prefix="crossx_"}async set(e,t){try{const r=JSON.stringify(t);localStorage.setItem(this.prefix+e,r)}catch(r){throw d.error("Storage set error:",r),r}}async get(e){try{const t=localStorage.getItem(this.prefix+e);return t?JSON.parse(t):null}catch(t){return d.error("Storage get error:",t),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(t){throw d.error("Storage remove error:",t),t}}async clear(){try{Object.keys(localStorage).forEach(t=>{t.startsWith(this.prefix)&&localStorage.removeItem(t)})}catch(e){throw d.error("Storage clear error:",e),e}}}const wt="crossx-sdk",cs=1,ce="data",Te="keys",St="aes-primary",Na=12;class ls{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,t)=>{const r=indexedDB.open(this.dbName,cs);r.onupgradeneeded=()=>{const n=r.result;n.objectStoreNames.contains(ce)||n.createObjectStore(ce),n.objectStoreNames.contains(Te)||n.createObjectStore(Te)},r.onsuccess=()=>e(r.result),r.onerror=()=>t(r.error)})}openLegacyIfExists(){return new Promise((e,t)=>{let r=!1;const n=indexedDB.open(wt,cs);n.onupgradeneeded=()=>{r=!0},n.onsuccess=()=>{const i=n.result;if(r){i.close(),this.deleteDB(wt).then(()=>e(null));return}if(!i.objectStoreNames.contains(Te)||!i.objectStoreNames.contains(ce)){i.close(),e(null);return}e(i)},n.onerror=()=>t(n.error)})}deleteDB(e){return new Promise(t=>{const r=indexedDB.deleteDatabase(e);r.onsuccess=()=>t(),r.onerror=()=>{d.warn("[CROSSx] IndexedDB 삭제 실패:",e,r.error),t()},r.onblocked=()=>{d.warn("[CROSSx] IndexedDB 삭제 보류 — 다른 탭이 DB 를 열고 있습니다:",e),t()}})}idbGet(e,t){return new Promise((r,n)=>{const a=this.db.transaction(e,"readonly").objectStore(e).get(t);a.onsuccess=()=>r(a.result),a.onerror=()=>n(a.error)})}idbPut(e,t,r){return new Promise((n,i)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).put(r,t);o.onsuccess=()=>n(),o.onerror=()=>i(o.error)})}idbDelete(e,t){return new Promise((r,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).delete(t);a.onsuccess=()=>r(),a.onerror=()=>n(a.error)})}idbClear(e){return new Promise((t,r)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>t(),i.onerror=()=>r(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Te,St);if(e){this.cryptoKey=e;return}const t=await this.migrateFromLegacyDB();if(t){this.cryptoKey=t;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Te,St,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===wt)return null;try{const e=await this.openLegacyIfExists();if(!e)return null;const t=e.transaction([Te,ce],"readonly"),r=t.objectStore(Te).get(St),n=await new Promise((u,f)=>{r.onsuccess=()=>u(r.result),r.onerror=()=>f(r.error)});if(!n)return e.close(),null;const i=t.objectStore(ce).getAll(),a=t.objectStore(ce).getAllKeys(),[o,c]=await Promise.all([new Promise((u,f)=>{i.onsuccess=()=>u(i.result),i.onerror=()=>f(i.error)}),new Promise((u,f)=>{a.onsuccess=()=>u(a.result),a.onerror=()=>f(a.error)})]);e.close(),await this.idbPut(Te,St,n);for(let u=0;u<c.length;u++)await this.idbPut(ce,String(c[u]),o[u]);return await this.deleteDB(wt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const t=new Uint8Array(Na);crypto.getRandomValues(t);const r=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},this.cryptoKey,r);return{iv:t,ciphertext:n}}async decrypt(e){const t=new Uint8Array(e.iv),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(r)}async set(e,t){try{await this.ensureReady();const r=JSON.stringify(t),n=await this.encrypt(r);await this.idbPut(ce,e,n)}catch(r){throw d.error("[CROSSx] IndexedDB set error:",r),r}}async get(e){try{await this.ensureReady();const t=await this.idbGet(ce,e);if(!t)return null;const r=await this.decrypt(t);return JSON.parse(r)}catch(t){return d.error("[CROSSx] IndexedDB get error:",t),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ce,e)}catch(t){throw d.error("[CROSSx] IndexedDB remove error:",t),t}}async clear(){try{await this.ensureReady(),await this.idbClear(ce)}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 Xt=crypto,ds=s=>s instanceof CryptoKey,Et=new TextEncoder,Qe=new TextDecoder;function Pa(...s){const e=s.reduce((n,{length:i})=>n+i,0),t=new Uint8Array(e);let r=0;for(const n of s)t.set(n,r),r+=n.length;return t}const ba=s=>{const e=atob(s),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ba(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class z extends Error{constructor(e,t){var r;super(e,t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)==null||r.call(Error,this,this.constructor)}}z.code="ERR_JOSE_GENERIC";class le extends z{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n,this.payload=t}}le.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class jt extends z{constructor(e,t,r="unspecified",n="unspecified"){super(e,{cause:{claim:r,reason:n,payload:t}}),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n,this.payload=t}}jt.code="ERR_JWT_EXPIRED";class hs extends z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}hs.code="ERR_JOSE_ALG_NOT_ALLOWED";class ue extends z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ue.code="ERR_JOSE_NOT_SUPPORTED";class xa extends z{constructor(e="decryption operation failed",t){super(e,t),this.code="ERR_JWE_DECRYPTION_FAILED"}}xa.code="ERR_JWE_DECRYPTION_FAILED";class va extends z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}va.code="ERR_JWE_INVALID";class q extends z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}q.code="ERR_JWS_INVALID";class fe extends z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}fe.code="ERR_JWT_INVALID";class Ca extends z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Ca.code="ERR_JWK_INVALID";class Zt extends z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Zt.code="ERR_JWKS_INVALID";class Qt extends z{constructor(e="no applicable key found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Qt.code="ERR_JWKS_NO_MATCHING_KEY";class us extends z{constructor(e="multiple matching keys found in the JSON Web Key Set",t){super(e,t),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}us.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class fs extends z{constructor(e="request timed out",t){super(e,t),this.code="ERR_JWKS_TIMEOUT"}}fs.code="ERR_JWKS_TIMEOUT";class gs extends z{constructor(e="signature verification failed",t){super(e,t),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}gs.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function ge(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 er(s){return parseInt(s.name.slice(4),10)}function Da(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ka(s,e){if(e.length&&!e.some(t=>s.usages.includes(t))){let t="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const r=e.pop();t+=`one of ${e.join(", ")}, or ${r}.`}else e.length===2?t+=`one of ${e[0]} or ${e[1]}.`:t+=`${e[0]}.`;throw new TypeError(t)}}function La(s,e,...t){switch(e){case"HS256":case"HS384":case"HS512":{if(!et(s.algorithm,"HMAC"))throw ge("HMAC");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!et(s.algorithm,"RSASSA-PKCS1-v1_5"))throw ge("RSASSA-PKCS1-v1_5");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!et(s.algorithm,"RSA-PSS"))throw ge("RSA-PSS");const r=parseInt(e.slice(2),10);if(er(s.algorithm.hash)!==r)throw ge(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw ge("Ed25519 or Ed448");break}case"Ed25519":{if(!et(s.algorithm,"Ed25519"))throw ge("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!et(s.algorithm,"ECDSA"))throw ge("ECDSA");const r=Da(e);if(s.algorithm.namedCurve!==r)throw ge(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ka(s,t)}function _s(s,e,...t){var r;if(t=t.filter(Boolean),t.length>2){const n=t.pop();s+=`one of type ${t.join(", ")}, or ${n}.`}else t.length===2?s+=`one of type ${t[0]} or ${t[1]}.`:s+=`of type ${t[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(r=e.constructor)!=null&&r.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const ps=(s,...e)=>_s("Key must be ",s,...e);function ws(s,e,...t){return _s(`Key for the ${s} algorithm must be `,e,...t)}const Ss=s=>ds(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",mt=["CryptoKey"],Ua=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let t;for(const r of e){const n=Object.keys(r);if(!t||t.size===0){t=new Set(n);continue}for(const i of n){if(t.has(i))return!1;t.add(i)}}return!0};function Wa(s){return typeof s=="object"&&s!==null}function Ee(s){if(!Wa(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 Ba=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:t}=e.algorithm;if(typeof t!="number"||t<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ke(s){return Ee(s)&&typeof s.kty=="string"}function Ma(s){return s.kty!=="oct"&&typeof s.d=="string"}function Fa(s){return s.kty!=="oct"&&typeof s.d>"u"}function Ka(s){return Ke(s)&&s.kty==="oct"&&typeof s.k=="string"}function Ha(s){let e,t;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},t=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},t=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}`},t=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},t=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},t=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},t=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},t=s.d?["deriveBits"]:[];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},t=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},t=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},t=s.d?["deriveBits"]:[];break;default:throw new ue('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new ue('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:t}}const Es=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:t}=Ha(s),r=[e,s.ext??!1,s.key_ops??t],n={...s};return delete n.alg,delete n.use,Xt.subtle.importKey("jwk",n,...r)},ms=s=>Re(s);let He,Ge;const ys=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",yt=async(s,e,t,r,n=!1)=>{let i=s.get(e);if(i!=null&&i[r])return i[r];const a=await Es({...t,alg:r});return n&&Object.freeze(e),i?i[r]=a:s.set(e,{[r]:a}),a},Ga={normalizePublicKey:(s,e)=>{if(ys(s)){let t=s.export({format:"jwk"});return delete t.d,delete t.dp,delete t.dq,delete t.p,delete t.q,delete t.qi,t.k?ms(t.k):(Ge||(Ge=new WeakMap),yt(Ge,s,t,e))}return Ke(s)?s.k?Re(s.k):(Ge||(Ge=new WeakMap),yt(Ge,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(ys(s)){let t=s.export({format:"jwk"});return t.k?ms(t.k):(He||(He=new WeakMap),yt(He,s,t,e))}return Ke(s)?s.k?Re(s.k):(He||(He=new WeakMap),yt(He,s,s,e,!0)):s}};async function As(s,e){if(!Ee(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 ue('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Es({...s,alg:e});default:throw new ue('Unsupported "kty" (Key Type) Parameter value')}}const $e=s=>s==null?void 0:s[Symbol.toStringTag],tr=(s,e,t)=>{var r,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=(r=e.key_ops).includes)==null?void 0:n.call(r,t))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${t}`);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},$a=(s,e,t,r)=>{if(!(e instanceof Uint8Array)){if(r&&Ke(e)){if(Ka(e)&&tr(s,e,t))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(!Ss(e))throw new TypeError(ws(s,e,...mt,"Uint8Array",r?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${$e(e)} instances for symmetric algorithms must be of type "secret"`)}},Va=(s,e,t,r)=>{if(r&&Ke(e))switch(t){case"sign":if(Ma(e)&&tr(s,e,t))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(Fa(e)&&tr(s,e,t))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ss(e))throw new TypeError(ws(s,e,...mt,r?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${$e(e)} instances for asymmetric algorithms must not be of type "secret"`);if(t==="sign"&&e.type==="public")throw new TypeError(`${$e(e)} instances for asymmetric algorithm signing must be of type "private"`);if(t==="decrypt"&&e.type==="public")throw new TypeError(`${$e(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&t==="verify"&&e.type==="private")throw new TypeError(`${$e(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&t==="encrypt"&&e.type==="private")throw new TypeError(`${$e(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Is(s,e,t,r){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?$a(e,t,r,s):Va(e,t,r,s)}Is.bind(void 0,!1);const Ts=Is.bind(void 0,!0);function Ja(s,e,t,r,n){if(n.crit!==void 0&&(r==null?void 0:r.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(a=>typeof a!="string"||a.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;t!==void 0?i=new Map([...Object.entries(t),...e.entries()]):i=e;for(const a of r.crit){if(!i.has(a))throw new ue(`Extension Header Parameter "${a}" is not recognized`);if(n[a]===void 0)throw new s(`Extension Header Parameter "${a}" is missing`);if(i.get(a)&&r[a]===void 0)throw new s(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)}const qa=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(t=>typeof t!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function Ya(s,e){const t=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:t,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:t,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:t,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:t,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ue(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function za(s,e,t){if(e=await Ga.normalizePublicKey(e,s),ds(e))return La(e,s,t),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(ps(e,...mt));return Xt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[t])}throw new TypeError(ps(e,...mt,"Uint8Array","JSON Web Key"))}const Xa=async(s,e,t,r)=>{const n=await za(s,e,"verify");Ba(s,n);const i=Ya(s,n.algorithm);try{return await Xt.subtle.verify(i,n,t,r)}catch{return!1}};async function ja(s,e,t){if(!Ee(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&&!Ee(s.header))throw new q("JWS Unprotected Header incorrect type");let r={};if(s.protected)try{const y=Re(s.protected);r=JSON.parse(Qe.decode(y))}catch{throw new q("JWS Protected Header is invalid")}if(!Ua(r,s.header))throw new q("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...r,...s.header},i=Ja(q,new Map([["b64",!0]]),t==null?void 0:t.crit,r,n);let a=!0;if(i.has("b64")&&(a=r.b64,typeof a!="boolean"))throw new q('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:o}=n;if(typeof o!="string"||!o)throw new q('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=t&&qa("algorithms",t.algorithms);if(c&&!c.has(o))throw new hs('"alg" (Algorithm) Header Parameter value not allowed');if(a){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 u=!1;typeof e=="function"?(e=await e(r,s),u=!0,Ts(o,e,"verify"),Ke(e)&&(e=await As(e,o))):Ts(o,e,"verify");const f=Pa(Et.encode(s.protected??""),Et.encode("."),typeof s.payload=="string"?Et.encode(s.payload):s.payload);let g;try{g=Re(s.signature)}catch{throw new q("Failed to base64url decode the signature")}if(!await Xa(o,e,g,f))throw new gs;let E;if(a)try{E=Re(s.payload)}catch{throw new q("Failed to base64url decode the payload")}else typeof s.payload=="string"?E=Et.encode(s.payload):E=s.payload;const m={payload:E};return s.protected!==void 0&&(m.protectedHeader=r),s.header!==void 0&&(m.unprotectedHeader=s.header),u?{...m,key:e}:m}async function Za(s,e,t){if(s instanceof Uint8Array&&(s=Qe.decode(s)),typeof s!="string")throw new q("Compact JWS must be a string or Uint8Array");const{0:r,1:n,2:i,length:a}=s.split(".");if(a!==3)throw new q("Invalid Compact JWS");const o=await ja({payload:n,protected:r,signature:i},e,t),c={payload:o.payload,protectedHeader:o.protectedHeader};return typeof e=="function"?{...c,key:o.key}:c}const Qa=s=>Math.floor(s.getTime()/1e3),Rs=60,Os=Rs*60,rr=Os*24,eo=rr*7,to=rr*365.25,ro=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ns=s=>{const e=ro.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const t=parseFloat(e[2]),r=e[3].toLowerCase();let n;switch(r){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(t);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(t*Rs);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(t*Os);break;case"day":case"days":case"d":n=Math.round(t*rr);break;case"week":case"weeks":case"w":n=Math.round(t*eo);break;default:n=Math.round(t*to);break}return e[1]==="-"||e[4]==="ago"?-n:n},Ps=s=>s.toLowerCase().replace(/^application\//,""),so=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,no=(s,e,t={})=>{let r;try{r=JSON.parse(Qe.decode(e))}catch{}if(!Ee(r))throw new fe("JWT Claims Set must be a top-level JSON object");const{typ:n}=t;if(n&&(typeof s.typ!="string"||Ps(s.typ)!==Ps(n)))throw new le('unexpected "typ" JWT header value',r,"typ","check_failed");const{requiredClaims:i=[],issuer:a,subject:o,audience:c,maxTokenAge:u}=t,f=[...i];u!==void 0&&f.push("iat"),c!==void 0&&f.push("aud"),o!==void 0&&f.push("sub"),a!==void 0&&f.push("iss");for(const m of new Set(f.reverse()))if(!(m in r))throw new le(`missing required "${m}" claim`,r,m,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(r.iss))throw new le('unexpected "iss" claim value',r,"iss","check_failed");if(o&&r.sub!==o)throw new le('unexpected "sub" claim value',r,"sub","check_failed");if(c&&!so(r.aud,typeof c=="string"?[c]:c))throw new le('unexpected "aud" claim value',r,"aud","check_failed");let g;switch(typeof t.clockTolerance){case"string":g=Ns(t.clockTolerance);break;case"number":g=t.clockTolerance;break;case"undefined":g=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:S}=t,E=Qa(S||new Date);if((r.iat!==void 0||u)&&typeof r.iat!="number")throw new le('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new le('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>E+g)throw new le('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new le('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=E-g)throw new jt('"exp" claim timestamp check failed',r,"exp","check_failed")}if(u){const m=E-r.iat,y=typeof u=="number"?u:Ns(u);if(m-g>y)throw new jt('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(m<0-g)throw new le('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r};async function io(s,e,t){var a;const r=await Za(s,e,t);if((a=r.protectedHeader.crit)!=null&&a.includes("b64")&&r.protectedHeader.b64===!1)throw new fe("JWTs MUST NOT use unencoded payload");const i={payload:no(r.protectedHeader,r.payload,t),protectedHeader:r.protectedHeader};return typeof e=="function"?{...i,key:r.key}:i}function ao(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 ue('Unsupported "alg" value for a JSON Web Key Set')}}function oo(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(co)}function co(s){return Ee(s)}function bs(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class lo{constructor(e){if(this._cached=new WeakMap,!oo(e))throw new Zt("JSON Web Key Set malformed");this._jwks=bs(e)}async getKey(e,t){const{alg:r,kid:n}={...e,...t==null?void 0:t.header},i=ao(r),a=this._jwks.keys.filter(u=>{let f=i===u.kty;if(f&&typeof n=="string"&&(f=n===u.kid),f&&typeof u.alg=="string"&&(f=r===u.alg),f&&typeof u.use=="string"&&(f=u.use==="sig"),f&&Array.isArray(u.key_ops)&&(f=u.key_ops.includes("verify")),f)switch(r){case"ES256":f=u.crv==="P-256";break;case"ES256K":f=u.crv==="secp256k1";break;case"ES384":f=u.crv==="P-384";break;case"ES512":f=u.crv==="P-521";break;case"Ed25519":f=u.crv==="Ed25519";break;case"EdDSA":f=u.crv==="Ed25519"||u.crv==="Ed448";break}return f}),{0:o,length:c}=a;if(c===0)throw new Qt;if(c!==1){const u=new us,{_cached:f}=this;throw u[Symbol.asyncIterator]=async function*(){for(const g of a)try{yield await xs(f,g,r)}catch{}},u}return xs(this._cached,o,r)}}async function xs(s,e,t){const r=s.get(e)||s.set(e,{}).get(e);if(r[t]===void 0){const n=await As({...e,ext:!0},t);if(n instanceof Uint8Array||n.type!=="public")throw new Zt("JSON Web Key Set members must be public keys");r[t]=n}return r[t]}function vs(s){const e=new lo(s),t=async(r,n)=>e.getKey(r,n);return Object.defineProperties(t,{jwks:{value:()=>bs(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),t}const ho=async(s,e,t)=>{let r,n,i=!1;typeof AbortController=="function"&&(r=new AbortController,n=setTimeout(()=>{i=!0,r.abort()},e));const a=await fetch(s.href,{signal:r?r.signal:void 0,redirect:"manual",headers:t.headers}).catch(o=>{throw i?new fs:o});if(n!==void 0&&clearTimeout(n),a.status!==200)throw new z("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new z("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function uo(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let sr;(typeof navigator>"u"||!((xn=(Ct=navigator.userAgent)==null?void 0:Ct.startsWith)!=null&&xn.call(Ct,"Mozilla/5.0 ")))&&(sr="jose/v5.10.0");const nr=Symbol();function fo(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Ee(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Ee))}class go{constructor(e,t){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:t==null?void 0:t.agent,headers:t==null?void 0:t.headers},this._timeoutDuration=typeof(t==null?void 0:t.timeoutDuration)=="number"?t==null?void 0:t.timeoutDuration:5e3,this._cooldownDuration=typeof(t==null?void 0:t.cooldownDuration)=="number"?t==null?void 0:t.cooldownDuration:3e4,this._cacheMaxAge=typeof(t==null?void 0:t.cacheMaxAge)=="number"?t==null?void 0:t.cacheMaxAge:6e5,(t==null?void 0:t[nr])!==void 0&&(this._cache=t==null?void 0:t[nr],fo(t==null?void 0:t[nr],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=vs(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,t){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,t)}catch(r){if(r instanceof Qt&&this.coolingDown()===!1)return await this.reload(),this._local(e,t);throw r}}async reload(){this._pendingFetch&&uo()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);sr&&!e.has("User-Agent")&&(e.set("User-Agent",sr),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ho(this._url,this._timeoutDuration,this._options).then(t=>{this._local=vs(t),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=t),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}}function _o(s,e){const t=new go(s,e),r=async(n,i)=>t.getKey(n,i);return Object.defineProperties(r,{coolingDown:{get:()=>t.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>t.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>t.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!t._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=t._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),r}const po=Re;function wo(s){if(typeof s!="string")throw new fe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:t}=s.split(".");if(t===5)throw new fe("Only JWTs using Compact JWS serialization can be decoded");if(t!==3)throw new fe("Invalid JWT");if(!e)throw new fe("JWTs must contain a payload");let r;try{r=po(e)}catch{throw new fe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Qe.decode(r))}catch{throw new fe("Failed to parse the decoded payload as JSON")}if(!Ee(n))throw new fe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ir(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function me(s,e=""){if(!Number.isSafeInteger(s)||s<0){const t=e&&`"${e}" `;throw new Error(`${t}expected integer >= 0, got ${s}`)}}function $(s,e,t=""){const r=ir(s),n=s==null?void 0:s.length,i=e!==void 0;if(!r||i&&n!==e){const a=t&&`"${t}" `,o=i?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof s}`;throw new Error(a+"expected Uint8Array"+o+", got "+c)}return s}function Cs(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");me(s.outputLen),me(s.blockLen)}function Ve(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 Ds(s,e){$(s,void 0,"digestInto() output");const t=e.outputLen;if(s.length<t)throw new Error('"digestInto() output" expected to be of length >='+t)}function So(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 ar(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function _e(s,e){return s<<32-e|s>>>e}const Eo=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function mo(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function yo(s){for(let e=0;e<s.length;e++)s[e]=mo(s[e]);return s}const ks=Eo?s=>s:yo,Ls=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ao=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function tt(s){if($(s),Ls)return s.toHex();let e="";for(let t=0;t<s.length;t++)e+=Ao[s[t]];return e}const ye={_0:48,_9:57,A:65,F:70,a:97,f:102};function Us(s){if(s>=ye._0&&s<=ye._9)return s-ye._0;if(s>=ye.A&&s<=ye.F)return s-(ye.A-10);if(s>=ye.a&&s<=ye.f)return s-(ye.a-10)}function At(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Ls)return Uint8Array.fromHex(s);const e=s.length,t=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(t);for(let n=0,i=0;n<t;n++,i+=2){const a=Us(s.charCodeAt(i)),o=Us(s.charCodeAt(i+1));if(a===void 0||o===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[n]=a*16+o}return r}function Oe(...s){let e=0;for(let r=0;r<s.length;r++){const n=s[r];$(n),e+=n.length}const t=new Uint8Array(e);for(let r=0,n=0;r<s.length;r++){const i=s[r];t.set(i,n),n+=i.length}return t}function Ws(s,e={}){const t=(n,i)=>s(i).update(n).digest(),r=s(void 0);return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=n=>s(n),Object.assign(t,e),Object.freeze(t)}function Bs(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 Io=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function To(s,e,t){return s&e^~s&t}function Ro(s,e,t){return s&e^s&t^e&t}class Oo{constructor(e,t,r,n){T(this,"blockLen");T(this,"outputLen");T(this,"padOffset");T(this,"isLE");T(this,"buffer");T(this,"view");T(this,"finished",!1);T(this,"length",0);T(this,"pos",0);T(this,"destroyed",!1);this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ar(this.buffer)}update(e){Ve(this),$(e);const{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let a=0;a<i;){const o=Math.min(n-this.pos,i-a);if(o===n){const c=ar(e);for(;n<=i-a;a+=n)this.process(c,a);continue}r.set(e.subarray(a,a+o),this.pos),this.pos+=o,a+=o,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ve(this),Ds(e,this),this.finished=!0;const{buffer:t,view:r,blockLen:n,isLE:i}=this;let{pos:a}=this;t[a++]=128,Je(this.buffer.subarray(a)),this.padOffset>n-a&&(this.process(r,0),a=0);for(let g=a;g<n;g++)t[g]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);const o=ar(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const u=c/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let g=0;g<u;g++)o.setUint32(4*g,f[g],i)}digest(){const{buffer:e,outputLen:t}=this;this.digestInto(e);const r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:t,buffer:r,length:n,finished:i,destroyed:a,pos:o}=this;return e.destroyed=a,e.finished=i,e.length=n,e.pos=o,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Ne=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),It=BigInt(2**32-1),Ms=BigInt(32);function No(s,e=!1){return e?{h:Number(s&It),l:Number(s>>Ms&It)}:{h:Number(s>>Ms&It)|0,l:Number(s&It)|0}}function Po(s,e=!1){const t=s.length;let r=new Uint32Array(t),n=new Uint32Array(t);for(let i=0;i<t;i++){const{h:a,l:o}=No(s[i],e);[r[i],n[i]]=[a,o]}return[r,n]}const bo=(s,e,t)=>s<<t|e>>>32-t,xo=(s,e,t)=>e<<t|s>>>32-t,vo=(s,e,t)=>e<<t-32|s>>>64-t,Co=(s,e,t)=>s<<t-32|e>>>64-t,Do=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pe=new Uint32Array(64);class ko extends Oo{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:t,C:r,D:n,E:i,F:a,G:o,H:c}=this;return[e,t,r,n,i,a,o,c]}set(e,t,r,n,i,a,o,c){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=c|0}process(e,t){for(let g=0;g<16;g++,t+=4)Pe[g]=e.getUint32(t,!1);for(let g=16;g<64;g++){const S=Pe[g-15],E=Pe[g-2],m=_e(S,7)^_e(S,18)^S>>>3,y=_e(E,17)^_e(E,19)^E>>>10;Pe[g]=y+Pe[g-7]+m+Pe[g-16]|0}let{A:r,B:n,C:i,D:a,E:o,F:c,G:u,H:f}=this;for(let g=0;g<64;g++){const S=_e(o,6)^_e(o,11)^_e(o,25),E=f+S+To(o,c,u)+Do[g]+Pe[g]|0,y=(_e(r,2)^_e(r,13)^_e(r,22))+Ro(r,n,i)|0;f=u,u=c,c=o,o=a+E|0,a=i,i=n,n=r,r=E+y|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,c=c+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,n,i,a,o,c,u,f)}roundClean(){Je(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Je(this.buffer)}}class Lo extends ko{constructor(){super(32);T(this,"A",Ne[0]|0);T(this,"B",Ne[1]|0);T(this,"C",Ne[2]|0);T(this,"D",Ne[3]|0);T(this,"E",Ne[4]|0);T(this,"F",Ne[5]|0);T(this,"G",Ne[6]|0);T(this,"H",Ne[7]|0)}}const Uo=Ws(()=>new Lo,Io(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const or=BigInt(0),cr=BigInt(1);function Tt(s,e=""){if(typeof s!="boolean"){const t=e&&`"${e}" `;throw new Error(t+"expected boolean, got type="+typeof s)}return s}function Fs(s){if(typeof s=="bigint"){if(!Nt(s))throw new Error("positive bigint expected, got "+s)}else me(s);return s}function Rt(s){const e=Fs(s).toString(16);return e.length&1?"0"+e:e}function Ks(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?or:BigInt("0x"+s)}function Ot(s){return Ks(tt(s))}function Hs(s){return Ks(tt(Wo($(s)).reverse()))}function lr(s,e){me(e),s=Fs(s);const t=At(s.toString(16).padStart(e*2,"0"));if(t.length!==e)throw new Error("number too large");return t}function Gs(s,e){return lr(s,e).reverse()}function Wo(s){return Uint8Array.from(s)}const Nt=s=>typeof s=="bigint"&&or<=s;function Bo(s,e,t){return Nt(s)&&Nt(e)&&Nt(t)&&e<=s&&s<t}function Mo(s,e,t,r){if(!Bo(e,t,r))throw new Error("expected valid "+s+": "+t+" <= n < "+r+", got "+e)}function Fo(s){let e;for(e=0;s>or;s>>=cr,e+=1);return e}const dr=s=>(cr<<BigInt(s))-cr;function Ko(s,e,t){if(me(s,"hashLen"),me(e,"qByteLen"),typeof t!="function")throw new Error("hmacFn must be a function");const r=w=>new Uint8Array(w),n=Uint8Array.of(),i=Uint8Array.of(0),a=Uint8Array.of(1),o=1e3;let c=r(s),u=r(s),f=0;const g=()=>{c.fill(1),u.fill(0),f=0},S=(...w)=>t(u,Oe(c,...w)),E=(w=n)=>{u=S(i,w),c=S(),w.length!==0&&(u=S(a,w),c=S())},m=()=>{if(f++>=o)throw new Error("drbg: tried max amount of iterations");let w=0;const A=[];for(;w<e;){c=S();const P=c.slice();A.push(P),w+=c.length}return Oe(...A)};return(w,A)=>{g(),E(w);let P;for(;!(P=A(m()));)E();return g(),P}}function hr(s,e={},t={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function r(i,a,o){const c=s[i];if(o&&c===void 0)return;const u=typeof c;if(u!==a||c===null)throw new Error(`param "${i}" is invalid: expected ${a}, got ${u}`)}const n=(i,a)=>Object.entries(i).forEach(([o,c])=>r(o,c,a));n(e,!1),n(t,!0)}function $s(s){const e=new WeakMap;return(t,...r)=>{const n=e.get(t);if(n!==void 0)return n;const i=s(t,...r);return e.set(t,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const se=BigInt(0),Q=BigInt(1),ve=BigInt(2),Vs=BigInt(3),Js=BigInt(4),qs=BigInt(5),Ho=BigInt(7),Ys=BigInt(8),Go=BigInt(9),zs=BigInt(16);function de(s,e){const t=s%e;return t>=se?t:e+t}function ae(s,e,t){let r=s;for(;e-- >se;)r*=r,r%=t;return r}function Xs(s,e){if(s===se)throw new Error("invert: expected non-zero number");if(e<=se)throw new Error("invert: expected positive modulus, got "+e);let t=de(s,e),r=e,n=se,i=Q;for(;t!==se;){const o=r/t,c=r%t,u=n-i*o;r=t,t=c,n=i,i=u}if(r!==Q)throw new Error("invert: does not exist");return de(n,e)}function ur(s,e,t){if(!s.eql(s.sqr(e),t))throw new Error("Cannot find square root")}function js(s,e){const t=(s.ORDER+Q)/Js,r=s.pow(e,t);return ur(s,r,e),r}function $o(s,e){const t=(s.ORDER-qs)/Ys,r=s.mul(e,ve),n=s.pow(r,t),i=s.mul(e,n),a=s.mul(s.mul(i,ve),n),o=s.mul(i,s.sub(a,s.ONE));return ur(s,o,e),o}function Vo(s){const e=Pt(s),t=Zs(s),r=t(e,e.neg(e.ONE)),n=t(e,r),i=t(e,e.neg(r)),a=(s+Ho)/zs;return(o,c)=>{let u=o.pow(c,a),f=o.mul(u,r);const g=o.mul(u,n),S=o.mul(u,i),E=o.eql(o.sqr(f),c),m=o.eql(o.sqr(g),c);u=o.cmov(u,f,E),f=o.cmov(S,g,m);const y=o.eql(o.sqr(f),c),w=o.cmov(u,f,y);return ur(o,w,c),w}}function Zs(s){if(s<Vs)throw new Error("sqrt is not defined for small field");let e=s-Q,t=0;for(;e%ve===se;)e/=ve,t++;let r=ve;const n=Pt(s);for(;en(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(t===1)return js;let i=n.pow(r,e);const a=(e+Q)/ve;return function(c,u){if(c.is0(u))return u;if(en(c,u)!==1)throw new Error("Cannot find square root");let f=t,g=c.mul(c.ONE,i),S=c.pow(u,e),E=c.pow(u,a);for(;!c.eql(S,c.ONE);){if(c.is0(S))return c.ZERO;let m=1,y=c.sqr(S);for(;!c.eql(y,c.ONE);)if(m++,y=c.sqr(y),m===f)throw new Error("Cannot find square root");const w=Q<<BigInt(f-m-1),A=c.pow(g,w);f=m,g=c.sqr(A),S=c.mul(S,g),E=c.mul(E,A)}return E}}function Jo(s){return s%Js===Vs?js:s%Ys===qs?$o:s%zs===Go?Vo(s):Zs(s)}const qo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Yo(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},t=qo.reduce((r,n)=>(r[n]="function",r),e);return hr(s,t),s}function zo(s,e,t){if(t<se)throw new Error("invalid exponent, negatives unsupported");if(t===se)return s.ONE;if(t===Q)return e;let r=s.ONE,n=e;for(;t>se;)t&Q&&(r=s.mul(r,n)),n=s.sqr(n),t>>=Q;return r}function Qs(s,e,t=!1){const r=new Array(e.length).fill(t?s.ZERO:void 0),n=e.reduce((a,o,c)=>s.is0(o)?a:(r[c]=a,s.mul(a,o)),s.ONE),i=s.inv(n);return e.reduceRight((a,o,c)=>s.is0(o)?a:(r[c]=s.mul(a,r[c]),s.mul(a,o)),i),r}function en(s,e){const t=(s.ORDER-Q)/ve,r=s.pow(e,t),n=s.eql(r,s.ONE),i=s.eql(r,s.ZERO),a=s.eql(r,s.neg(s.ONE));if(!n&&!i&&!a)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Xo(s,e){e!==void 0&&me(e);const t=e!==void 0?e:s.toString(2).length,r=Math.ceil(t/8);return{nBitLength:t,nByteLength:r}}class jo{constructor(e,t={}){T(this,"ORDER");T(this,"BITS");T(this,"BYTES");T(this,"isLE");T(this,"ZERO",se);T(this,"ONE",Q);T(this,"_lengths");T(this,"_sqrt");T(this,"_mod");var a;if(e<=se)throw new Error("invalid field: expected ORDER > 0, got "+e);let r;this.isLE=!1,t!=null&&typeof t=="object"&&(typeof t.BITS=="number"&&(r=t.BITS),typeof t.sqrt=="function"&&(this.sqrt=t.sqrt),typeof t.isLE=="boolean"&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=(a=t.allowedLengths)==null?void 0:a.slice()),typeof t.modFromBytes=="boolean"&&(this._mod=t.modFromBytes));const{nBitLength:n,nByteLength:i}=Xo(e,r);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 de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return se<=e&&e<this.ORDER}is0(e){return e===se}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return de(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return de(e*e,this.ORDER)}add(e,t){return de(e+t,this.ORDER)}sub(e,t){return de(e-t,this.ORDER)}mul(e,t){return de(e*t,this.ORDER)}pow(e,t){return zo(this,e,t)}div(e,t){return de(e*Xs(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return Xs(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Jo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Gs(e,this.BYTES):lr(e,this.BYTES)}fromBytes(e,t=!1){$(e);const{_lengths:r,BYTES:n,isLE:i,ORDER:a,_mod:o}=this;if(r){if(!r.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+r+" bytes, got "+e.length);const u=new Uint8Array(n);u.set(e,i?0:u.length-e.length),e=u}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Hs(e):Ot(e);if(o&&(c=de(c,a)),!t&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Qs(this,e)}cmov(e,t,r){return r?t:e}}function Pt(s,e={}){return new jo(s,e)}function tn(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 rn(s){const e=tn(s);return e+Math.ceil(e/2)}function Zo(s,e,t=!1){$(s);const r=s.length,n=tn(e),i=rn(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const a=t?Hs(s):Ot(s),o=de(a,e-Q)+Q;return t?Gs(o,n):lr(o,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),Ce=BigInt(1);function bt(s,e){const t=e.negate();return s?t:e}function sn(s,e){const t=Qs(s.Fp,e.map(r=>r.Z));return e.map((r,n)=>s.fromAffine(r.toAffine(t[n])))}function nn(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function fr(s,e){nn(s,e);const t=Math.ceil(e/s)+1,r=2**(s-1),n=2**s,i=dr(s),a=BigInt(s);return{windows:t,windowSize:r,mask:i,maxNumber:n,shiftBy:a}}function an(s,e,t){const{windowSize:r,mask:n,maxNumber:i,shiftBy:a}=t;let o=Number(s&n),c=s>>a;o>r&&(o-=i,c+=Ce);const u=e*r,f=u+Math.abs(o)-1,g=o===0,S=o<0,E=e%2!==0;return{nextN:c,offset:f,isZero:g,isNeg:S,isNegF:E,offsetF:u}}const gr=new WeakMap,on=new WeakMap;function _r(s){return on.get(s)||1}function cn(s){if(s!==qe)throw new Error("invalid wNAF")}class Qo{constructor(e,t){T(this,"BASE");T(this,"ZERO");T(this,"Fn");T(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=t}_unsafeLadder(e,t,r=this.ZERO){let n=e;for(;t>qe;)t&Ce&&(r=r.add(n)),n=n.double(),t>>=Ce;return r}precomputeWindow(e,t){const{windows:r,windowSize:n}=fr(t,this.bits),i=[];let a=e,o=a;for(let c=0;c<r;c++){o=a,i.push(o);for(let u=1;u<n;u++)o=o.add(a),i.push(o);a=o.double()}return i}wNAF(e,t,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const a=fr(e,this.bits);for(let o=0;o<a.windows;o++){const{nextN:c,offset:u,isZero:f,isNeg:g,isNegF:S,offsetF:E}=an(r,o,a);r=c,f?i=i.add(bt(S,t[E])):n=n.add(bt(g,t[u]))}return cn(r),{p:n,f:i}}wNAFUnsafe(e,t,r,n=this.ZERO){const i=fr(e,this.bits);for(let a=0;a<i.windows&&r!==qe;a++){const{nextN:o,offset:c,isZero:u,isNeg:f}=an(r,a,i);if(r=o,!u){const g=t[c];n=n.add(f?g.negate():g)}}return cn(r),n}getPrecomputes(e,t,r){let n=gr.get(t);return n||(n=this.precomputeWindow(t,e),e!==1&&(typeof r=="function"&&(n=r(n)),gr.set(t,n))),n}cached(e,t,r){const n=_r(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)}unsafe(e,t,r,n){const i=_r(e);return i===1?this._unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)}createCache(e,t){nn(t,this.bits),on.set(e,t),gr.delete(e)}hasCache(e){return _r(e)!==1}}function ec(s,e,t,r){let n=e,i=s.ZERO,a=s.ZERO;for(;t>qe||r>qe;)t&Ce&&(i=i.add(n)),r&Ce&&(a=a.add(n)),n=n.double(),t>>=Ce,r>>=Ce;return{p1:i,p2:a}}function ln(s,e,t){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Yo(e),e}else return Pt(s,{isLE:t})}function tc(s,e,t={},r){if(r===void 0&&(r=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>qe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=ln(e.p,t.Fp,r),i=ln(e.n,t.Fn,r),o=["Gx","Gy","a","b"];for(const c of o)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 rc(s,e){return function(r){const n=s(r);return{secretKey:n,publicKey:e(n)}}}class dn{constructor(e,t){T(this,"oHash");T(this,"iHash");T(this,"blockLen");T(this,"outputLen");T(this,"finished",!1);T(this,"destroyed",!1);if(Cs(e),$(t,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 r=this.blockLen,n=new Uint8Array(r);n.set(t.length>r?e.create().update(t).digest():t);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 Ve(this),this.iHash.update(e),this}digestInto(e){Ve(this),$(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:t,iHash:r,finished:n,destroyed:i,blockLen:a,outputLen:o}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const hn=(s,e,t)=>new dn(s,e).update(t).digest();hn.create=(s,e)=>new dn(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const un=(s,e)=>(s+(s>=0?e:-e)/fn)/e;function sc(s,e,t){const[[r,n],[i,a]]=e,o=un(a*s,t),c=un(-n*s,t);let u=s-o*r-c*i,f=-o*n-c*a;const g=u<Ae,S=f<Ae;g&&(u=-u),S&&(f=-f);const E=dr(Math.ceil(Fo(t)/2))+Ye;if(u<Ae||u>=E||f<Ae||f>=E)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:g,k1:u,k2neg:S,k2:f}}function pr(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function wr(s,e){const t={};for(let r of Object.keys(e))t[r]=s[r]===void 0?e[r]:s[r];return Tt(t.lowS,"lowS"),Tt(t.prehash,"prehash"),t.format!==void 0&&pr(t.format),t}class nc extends Error{constructor(e=""){super(e)}}const be={Err:nc,_tlv:{encode:(s,e)=>{const{Err:t}=be;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length&1)throw new t("tlv.encode: unpadded data");const r=e.length/2,n=Rt(r);if(n.length/2&128)throw new t("tlv.encode: long form length too big");const i=r>127?Rt(n.length/2|128):"";return Rt(s)+i+n+e},decode(s,e){const{Err:t}=be;let r=0;if(s<0||s>256)throw new t("tlv.encode: wrong tag");if(e.length<2||e[r++]!==s)throw new t("tlv.decode: wrong tlv");const n=e[r++],i=!!(n&128);let a=0;if(!i)a=n;else{const c=n&127;if(!c)throw new t("tlv.decode(long): indefinite length not supported");if(c>4)throw new t("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new t("tlv.decode: length bytes not complete");if(u[0]===0)throw new t("tlv.decode(long): zero leftmost byte");for(const f of u)a=a<<8|f;if(r+=c,a<128)throw new t("tlv.decode(long): not minimal encoding")}const o=e.subarray(r,r+a);if(o.length!==a)throw new t("tlv.decode: wrong value length");return{v:o,l:e.subarray(r+a)}}},_int:{encode(s){const{Err:e}=be;if(s<Ae)throw new e("integer: negative integers are not allowed");let t=Rt(s);if(Number.parseInt(t[0],16)&8&&(t="00"+t),t.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return t},decode(s){const{Err:e}=be;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 Ot(s)}},toSig(s){const{Err:e,_int:t,_tlv:r}=be,n=$(s,void 0,"signature"),{v:i,l:a}=r.decode(48,n);if(a.length)throw new e("invalid signature: left bytes after parsing");const{v:o,l:c}=r.decode(2,i),{v:u,l:f}=r.decode(2,c);if(f.length)throw new e("invalid signature: left bytes after parsing");return{r:t.decode(o),s:t.decode(u)}},hexFromSig(s){const{_tlv:e,_int:t}=be,r=e.encode(2,t.encode(s.r)),n=e.encode(2,t.encode(s.s)),i=r+n;return e.encode(48,i)}},Ae=BigInt(0),Ye=BigInt(1),fn=BigInt(2),xt=BigInt(3),ic=BigInt(4);function ac(s,e={}){const t=tc("weierstrass",s,e),{Fp:r,Fn:n}=t;let i=t.CURVE;const{h:a,n:o}=i;hr(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=_n(r,n);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function g(k,_,p){const{x:I,y:R}=_.toAffine(),b=r.toBytes(I);if(Tt(p,"isCompressed"),p){f();const N=!r.isOdd(R);return Oe(gn(N),b)}else return Oe(Uint8Array.of(4),b,r.toBytes(R))}function S(k){$(k,void 0,"Point");const{publicKey:_,publicKeyUncompressed:p}=u,I=k.length,R=k[0],b=k.subarray(1);if(I===_&&(R===2||R===3)){const N=r.fromBytes(b);if(!r.isValid(N))throw new Error("bad point: is not on curve, wrong x");const x=y(N);let O;try{O=r.sqrt(x)}catch(Y){const G=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+G)}f();const C=r.isOdd(O);return(R&1)===1!==C&&(O=r.neg(O)),{x:N,y:O}}else if(I===p&&R===4){const N=r.BYTES,x=r.fromBytes(b.subarray(0,N)),O=r.fromBytes(b.subarray(N,N*2));if(!w(x,O))throw new Error("bad point: is not on curve");return{x,y:O}}else throw new Error(`bad point: got length ${I}, expected compressed=${_} or uncompressed=${p}`)}const E=e.toBytes||g,m=e.fromBytes||S;function y(k){const _=r.sqr(k),p=r.mul(_,k);return r.add(r.add(p,r.mul(k,i.a)),i.b)}function w(k,_){const p=r.sqr(_),I=y(k);return r.eql(p,I)}if(!w(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=r.mul(r.pow(i.a,xt),ic),P=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(A,P)))throw new Error("bad curve params: a or b");function F(k,_,p=!1){if(!r.isValid(_)||p&&r.is0(_))throw new Error(`bad point coordinate ${k}`);return _}function M(k){if(!(k instanceof v))throw new Error("Weierstrass Point expected")}function V(k){if(!c||!c.basises)throw new Error("no endo");return sc(k,c.basises,n.ORDER)}const U=$s((k,_)=>{const{X:p,Y:I,Z:R}=k;if(r.eql(R,r.ONE))return{x:p,y:I};const b=k.is0();_==null&&(_=b?r.ONE:r.inv(R));const N=r.mul(p,_),x=r.mul(I,_),O=r.mul(R,_);if(b)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:N,y:x}}),H=$s(k=>{if(k.is0()){if(e.allowInfinityPoint&&!r.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:p}=k.toAffine();if(!r.isValid(_)||!r.isValid(p))throw new Error("bad point: x or y not field elements");if(!w(_,p))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Z(k,_,p,I,R){return p=new v(r.mul(p.X,k),p.Y,p.Z),_=bt(I,_),p=bt(R,p),_.add(p)}const K=class K{constructor(_,p,I){T(this,"X");T(this,"Y");T(this,"Z");this.X=F("x",_),this.Y=F("y",p,!0),this.Z=F("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(_){const{x:p,y:I}=_||{};if(!_||!r.isValid(p)||!r.isValid(I))throw new Error("invalid affine point");if(_ instanceof K)throw new Error("projective point not allowed");return r.is0(p)&&r.is0(I)?K.ZERO:new K(p,I,r.ONE)}static fromBytes(_){const p=K.fromAffine(m($(_,void 0,"point")));return p.assertValidity(),p}static fromHex(_){return K.fromBytes(At(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,p=!0){return B.createCache(this,_),p||this.multiply(xt),this}assertValidity(){H(this)}hasEvenY(){const{y:_}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(_)}equals(_){M(_);const{X:p,Y:I,Z:R}=this,{X:b,Y:N,Z:x}=_,O=r.eql(r.mul(p,x),r.mul(b,R)),C=r.eql(r.mul(I,x),r.mul(N,R));return O&&C}negate(){return new K(this.X,r.neg(this.Y),this.Z)}double(){const{a:_,b:p}=i,I=r.mul(p,xt),{X:R,Y:b,Z:N}=this;let x=r.ZERO,O=r.ZERO,C=r.ZERO,L=r.mul(R,R),Y=r.mul(b,b),G=r.mul(N,N),D=r.mul(R,b);return D=r.add(D,D),C=r.mul(R,N),C=r.add(C,C),x=r.mul(_,C),O=r.mul(I,G),O=r.add(x,O),x=r.sub(Y,O),O=r.add(Y,O),O=r.mul(x,O),x=r.mul(D,x),C=r.mul(I,C),G=r.mul(_,G),D=r.sub(L,G),D=r.mul(_,D),D=r.add(D,C),C=r.add(L,L),L=r.add(C,L),L=r.add(L,G),L=r.mul(L,D),O=r.add(O,L),G=r.mul(b,N),G=r.add(G,G),L=r.mul(G,D),x=r.sub(x,L),C=r.mul(G,Y),C=r.add(C,C),C=r.add(C,C),new K(x,O,C)}add(_){M(_);const{X:p,Y:I,Z:R}=this,{X:b,Y:N,Z:x}=_;let O=r.ZERO,C=r.ZERO,L=r.ZERO;const Y=i.a,G=r.mul(i.b,xt);let D=r.mul(p,b),X=r.mul(I,N),te=r.mul(R,x),ne=r.add(p,I),J=r.add(b,N);ne=r.mul(ne,J),J=r.add(D,X),ne=r.sub(ne,J),J=r.add(p,R);let re=r.add(b,x);return J=r.mul(J,re),re=r.add(D,te),J=r.sub(J,re),re=r.add(I,R),O=r.add(N,x),re=r.mul(re,O),O=r.add(X,te),re=r.sub(re,O),L=r.mul(Y,J),O=r.mul(G,te),L=r.add(O,L),O=r.sub(X,L),L=r.add(X,L),C=r.mul(O,L),X=r.add(D,D),X=r.add(X,D),te=r.mul(Y,te),J=r.mul(G,J),X=r.add(X,te),te=r.sub(D,te),te=r.mul(Y,te),J=r.add(J,te),D=r.mul(X,J),C=r.add(C,D),D=r.mul(re,J),O=r.mul(ne,O),O=r.sub(O,D),D=r.mul(ne,X),L=r.mul(re,L),L=r.add(L,D),new K(O,C,L)}subtract(_){return this.add(_.negate())}is0(){return this.equals(K.ZERO)}multiply(_){const{endo:p}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let I,R;const b=N=>B.cached(this,N,x=>sn(K,x));if(p){const{k1neg:N,k1:x,k2neg:O,k2:C}=V(_),{p:L,f:Y}=b(x),{p:G,f:D}=b(C);R=Y.add(D),I=Z(p.beta,L,G,N,O)}else{const{p:N,f:x}=b(_);I=N,R=x}return sn(K,[I,R])[0]}multiplyUnsafe(_){const{endo:p}=e,I=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===Ae||I.is0())return K.ZERO;if(_===Ye)return I;if(B.hasCache(this))return this.multiply(_);if(p){const{k1neg:R,k1:b,k2neg:N,k2:x}=V(_),{p1:O,p2:C}=ec(K,I,b,x);return Z(p.beta,O,C,R,N)}else return B.unsafe(I,_)}toAffine(_){return U(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return a===Ye?!0:_?_(K,this):B.unsafe(this,o).is0()}clearCofactor(){const{clearCofactor:_}=e;return a===Ye?this:_?_(K,this):this.multiplyUnsafe(a)}isSmallOrder(){return this.multiplyUnsafe(a).is0()}toBytes(_=!0){return Tt(_,"isCompressed"),this.assertValidity(),E(K,this,_)}toHex(_=!0){return tt(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};T(K,"BASE",new K(i.Gx,i.Gy,r.ONE)),T(K,"ZERO",new K(r.ZERO,r.ONE,r.ZERO)),T(K,"Fp",r),T(K,"Fn",n);let v=K;const ee=n.BITS,B=new Qo(v,e.endo?Math.ceil(ee/2):ee);return v.BASE.precompute(8),v}function gn(s){return Uint8Array.of(s?2:3)}function _n(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function oc(s,e={}){const{Fn:t}=s,r=e.randomBytes||Bs,n=Object.assign(_n(s.Fp,t),{seed:rn(t.ORDER)});function i(E){try{const m=t.fromBytes(E);return t.isValidNot0(m)}catch{return!1}}function a(E,m){const{publicKey:y,publicKeyUncompressed:w}=n;try{const A=E.length;return m===!0&&A!==y||m===!1&&A!==w?!1:!!s.fromBytes(E)}catch{return!1}}function o(E=r(n.seed)){return Zo($(E,n.seed,"seed"),t.ORDER)}function c(E,m=!0){return s.BASE.multiply(t.fromBytes(E)).toBytes(m)}function u(E){const{secretKey:m,publicKey:y,publicKeyUncompressed:w}=n;if(!ir(E)||"_lengths"in t&&t._lengths||m===y)return;const A=$(E,void 0,"key").length;return A===y||A===w}function f(E,m,y=!0){if(u(E)===!0)throw new Error("first arg must be private key");if(u(m)===!1)throw new Error("second arg must be public key");const w=t.fromBytes(E);return s.fromBytes(m).multiply(w).toBytes(y)}const g={isValidSecretKey:i,isValidPublicKey:a,randomSecretKey:o},S=rc(o,c);return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:S,Point:s,utils:g,lengths:n})}function cc(s,e,t={}){Cs(e),hr(t,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),t=Object.assign({},t);const r=t.randomBytes||Bs,n=t.hmac||((_,p)=>hn(e,_,p)),{Fp:i,Fn:a}=s,{ORDER:o,BITS:c}=a,{keygen:u,getPublicKey:f,getSharedSecret:g,utils:S,lengths:E}=oc(s,t),m={prehash:!0,lowS:typeof t.lowS=="boolean"?t.lowS:!0,format:"compact",extraEntropy:!1},y=o*fn<i.ORDER;function w(_){const p=o>>Ye;return _>p}function A(_,p){if(!a.isValidNot0(p))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return p}function P(){if(y)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function F(_,p){pr(p);const I=E.signature,R=p==="compact"?I:p==="recovered"?I+1:void 0;return $(_,R)}class M{constructor(p,I,R){T(this,"r");T(this,"s");T(this,"recovery");if(this.r=A("r",p),this.s=A("s",I),R!=null){if(P(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(p,I=m.format){F(p,I);let R;if(I==="der"){const{r:O,s:C}=be.toSig($(p));return new M(O,C)}I==="recovered"&&(R=p[0],I="compact",p=p.subarray(1));const b=E.signature/2,N=p.subarray(0,b),x=p.subarray(b,b*2);return new M(a.fromBytes(N),a.fromBytes(x),R)}static fromHex(p,I){return this.fromBytes(At(p),I)}assertRecovery(){const{recovery:p}=this;if(p==null)throw new Error("invalid recovery id: must be present");return p}addRecoveryBit(p){return new M(this.r,this.s,p)}recoverPublicKey(p){const{r:I,s:R}=this,b=this.assertRecovery(),N=b===2||b===3?I+o:I;if(!i.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const x=i.toBytes(N),O=s.fromBytes(Oe(gn((b&1)===0),x)),C=a.inv(N),L=U($(p,void 0,"msgHash")),Y=a.create(-L*C),G=a.create(R*C),D=s.BASE.multiplyUnsafe(Y).add(O.multiplyUnsafe(G));if(D.is0())throw new Error("invalid recovery: point at infinify");return D.assertValidity(),D}hasHighS(){return w(this.s)}toBytes(p=m.format){if(pr(p),p==="der")return At(be.hexFromSig(this));const{r:I,s:R}=this,b=a.toBytes(I),N=a.toBytes(R);return p==="recovered"?(P(),Oe(Uint8Array.of(this.assertRecovery()),b,N)):Oe(b,N)}toHex(p){return tt(this.toBytes(p))}}const V=t.bits2int||function(p){if(p.length>8192)throw new Error("input is too large");const I=Ot(p),R=p.length*8-c;return R>0?I>>BigInt(R):I},U=t.bits2int_modN||function(p){return a.create(V(p))},H=dr(c);function Z(_){return Mo("num < 2^"+c,_,Ae,H),a.toBytes(_)}function v(_,p){return $(_,void 0,"message"),p?$(e(_),void 0,"prehashed message"):_}function ee(_,p,I){const{lowS:R,prehash:b,extraEntropy:N}=wr(I,m);_=v(_,b);const x=U(_),O=a.fromBytes(p);if(!a.isValidNot0(O))throw new Error("invalid private key");const C=[Z(O),Z(x)];if(N!=null&&N!==!1){const D=N===!0?r(E.secretKey):N;C.push($(D,void 0,"extraEntropy"))}const L=Oe(...C),Y=x;function G(D){const X=V(D);if(!a.isValidNot0(X))return;const te=a.inv(X),ne=s.BASE.multiply(X).toAffine(),J=a.create(ne.x);if(J===Ae)return;const re=a.create(te*a.create(Y+J*O));if(re===Ae)return;let vn=(ne.x===J?0:2)|Number(ne.y&Ye),Cn=re;return R&&w(re)&&(Cn=a.neg(re),vn^=1),new M(J,Cn,y?void 0:vn)}return{seed:L,k2sig:G}}function B(_,p,I={}){const{seed:R,k2sig:b}=ee(_,p,I);return Ko(e.outputLen,a.BYTES,n)(R,b).toBytes(I.format)}function K(_,p,I,R={}){const{lowS:b,prehash:N,format:x}=wr(R,m);if(I=$(I,void 0,"publicKey"),p=v(p,N),!ir(_)){const O=_ instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}F(_,x);try{const O=M.fromBytes(_,x),C=s.fromBytes(I);if(b&&O.hasHighS())return!1;const{r:L,s:Y}=O,G=U(p),D=a.inv(Y),X=a.create(G*D),te=a.create(L*D),ne=s.BASE.multiplyUnsafe(X).add(C.multiplyUnsafe(te));return ne.is0()?!1:a.create(ne.x)===L}catch{return!1}}function k(_,p,I={}){const{prehash:R}=wr(I,m);return p=v(p,R),M.fromBytes(_,"recovered").recoverPublicKey(p).toBytes()}return Object.freeze({keygen:u,getPublicKey:f,getSharedSecret:g,utils:S,lengths:E,Point:s,sign:B,verify:K,recoverPublicKey:k,Signature:M,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},lc={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},pn=BigInt(2);function dc(s){const e=Sr.p,t=BigInt(3),r=BigInt(6),n=BigInt(11),i=BigInt(22),a=BigInt(23),o=BigInt(44),c=BigInt(88),u=s*s*s%e,f=u*u*s%e,g=ae(f,t,e)*f%e,S=ae(g,t,e)*f%e,E=ae(S,pn,e)*u%e,m=ae(E,n,e)*E%e,y=ae(m,i,e)*m%e,w=ae(y,o,e)*y%e,A=ae(w,c,e)*w%e,P=ae(A,o,e)*y%e,F=ae(P,t,e)*f%e,M=ae(F,a,e)*m%e,V=ae(M,r,e)*u%e,U=ae(V,pn,e);if(!Er.eql(Er.sqr(U),s))throw new Error("Cannot find square root");return U}const Er=Pt(Sr.p,{sqrt:dc}),hc=cc(ac(Sr,{Fp:Er,endo:lc}),Uo),uc=BigInt(0),rt=BigInt(1),fc=BigInt(2),gc=BigInt(7),_c=BigInt(256),pc=BigInt(113),wn=[],Sn=[],En=[];for(let s=0,e=rt,t=1,r=0;s<24;s++){[t,r]=[r,(2*t+3*r)%5],wn.push(2*(5*r+t)),Sn.push((s+1)*(s+2)/2%64);let n=uc;for(let i=0;i<7;i++)e=(e<<rt^(e>>gc)*pc)%_c,e&fc&&(n^=rt<<(rt<<BigInt(i))-rt);En.push(n)}const mn=Po(En,!0),wc=mn[0],Sc=mn[1],yn=(s,e,t)=>t>32?vo(s,e,t):bo(s,e,t),An=(s,e,t)=>t>32?Co(s,e,t):xo(s,e,t);function Ec(s,e=24){const t=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let a=0;a<10;a++)t[a]=s[a]^s[a+10]^s[a+20]^s[a+30]^s[a+40];for(let a=0;a<10;a+=2){const o=(a+8)%10,c=(a+2)%10,u=t[c],f=t[c+1],g=yn(u,f,1)^t[o],S=An(u,f,1)^t[o+1];for(let E=0;E<50;E+=10)s[a+E]^=g,s[a+E+1]^=S}let n=s[2],i=s[3];for(let a=0;a<24;a++){const o=Sn[a],c=yn(n,i,o),u=An(n,i,o),f=wn[a];n=s[f],i=s[f+1],s[f]=c,s[f+1]=u}for(let a=0;a<50;a+=10){for(let o=0;o<10;o++)t[o]=s[a+o];for(let o=0;o<10;o++)s[a+o]^=~t[(o+2)%10]&t[(o+4)%10]}s[0]^=wc[r],s[1]^=Sc[r]}Je(t)}class mr{constructor(e,t,r,n=!1,i=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=e,this.suffix=t,this.outputLen=r,this.enableXOF=n,this.rounds=i,me(r,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=So(this.state)}clone(){return this._cloneInto()}keccak(){ks(this.state32),Ec(this.state32,this.rounds),ks(this.state32),this.posOut=0,this.pos=0}update(e){Ve(this),$(e);const{blockLen:t,state:r}=this,n=e.length;for(let i=0;i<n;){const a=Math.min(t-this.pos,n-i);for(let o=0;o<a;o++)r[this.pos++]^=e[i++];this.pos===t&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:t,pos:r,blockLen:n}=this;e[r]^=t,(t&128)!==0&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ve(this,!1),$(e),this.finish();const t=this.state,{blockLen:r}=this;for(let n=0,i=e.length;n<i;){this.posOut>=r&&this.keccak();const a=Math.min(r-this.posOut,i-n);e.set(t.subarray(this.posOut,this.posOut+a),n),this.posOut+=a,n+=a}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return me(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Ds(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:t,suffix:r,outputLen:n,rounds:i,enableXOF:a}=this;return e||(e=new mr(t,r,n,a,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=n,e.enableXOF=a,e.destroyed=this.destroyed,e}}const In=((s,e,t,r={})=>Ws(()=>new mr(e,s,t),r))(1,136,32),mc=60;class yc{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=_o(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(t){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",t)}}async verifyJWT(e,t){try{const r=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:r.sub,exp:r.exp,iat:r.iat});const n=Math.floor(Date.now()/1e3);if(r.exp&&r.exp+mc<n)return d.warn("[CROSSx] 토큰 만료:",{exp:r.exp,now:n,만료시간:new Date(r.exp*1e3).toISOString()}),{payload:r,valid:!1,signatureVerified:!1};if(!r.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:r,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await io(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:r,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:r,valid:!0,signatureVerified:!1}}catch(r){throw d.error("[CROSSx] JWT 검증 중 에러:",r),r}}decodeJWT(e){return wo(e)}recoverPersonalSignSigner(e,t){const r=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
7
+ ${r.length}`),i=new Uint8Array(n.length+r.length);i.set(n,0),i.set(r,n.length);const a=In(i),o=t.startsWith("0x")?t.slice(2):t;if(o.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${o.length}`);const c=Ac(o),u=c.slice(0,32),f=c.slice(32,64),g=c[64],S=g>=27?g-27:g,y=new hc.Signature(Tn(u),Tn(f)).addRecoveryBit(S).recoverPublicKey(a).toBytes(!1).slice(1),w=In(y);return"0x"+tt(w.slice(12))}}function Ac(s){const e=new Uint8Array(s.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(s.substring(t*2,t*2+2),16);return e}function Tn(s){let e="0x";for(const t of s)e+=t.toString(16).padStart(2,"0");return BigInt(e)}const Ic=5e3;class Tc{constructor(e,t){this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyInFlight=null,this.keyFailedAt=0,this.required=!1,this.adapterConfig=e,this.transport=t}get baseUrl(){return this.adapterConfig.gatewayUrl}async seal(e){if(!e)return e;const t=this.required;if(!t&&this.hasFreshFailure())return e;try{const{version:r,key:n}=await this.currentKey(),i=await Rc(n,e);return`${r}.${Oc(i)}`}catch(r){if(t)throw this.keyFailedAt=Date.now(),r instanceof h?r:new h(l.PIN_ENCRYPTION_FAILED,"PIN 암호화에 실패했습니다. 잠시 후 다시 시도해 주세요.",{cause:String(r)});return this.keyFailedAt=Date.now(),d.warn("[CROSSx] pin-key 조회 실패 — PIN 평문 전송을 유지합니다",`(${Math.round(Pr/1e3)}초 후 재확인)`),e}}invalidate(){d.log("[CROSSx] PIN 공개키 캐시 무효화"),this.cachedKey=null,this.cachedVersion=null,this.cachedAt=0,this.keyFailedAt=0,this.keyInFlight=null}requireEncryption(){this.required||(d.warn("[CROSSx] 게이트웨이가 PIN 암호화를 요구함 — 이후 요청은 항상 암호화합니다"),this.required=!0)}prewarm(){this.currentKey().then(()=>{},()=>{})}hasFreshFailure(){return this.keyFailedAt!==0&&Date.now()-this.keyFailedAt<Pr}async currentKey(){return this.cachedKey&&this.cachedVersion&&Date.now()-this.cachedAt<Mn?{version:this.cachedVersion,key:this.cachedKey}:this.keyInFlight?this.keyInFlight:(this.keyInFlight=this.fetchAndImportKey().then(e=>(this.cachedVersion=e.version,this.cachedKey=e.key,this.cachedAt=Date.now(),this.keyFailedAt=0,d.log("[CROSSx] PIN 공개키 캐시 완료 (keyVersion:",e.version,")"),e)).finally(()=>{this.keyInFlight=null}),this.keyInFlight)}async fetchAndImportKey(){const e=Rn();if(!e)throw new h(l.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다. HTTPS 환경에서 다시 시도해 주세요.");const t=await this.transport.request({url:`${this.baseUrl}/pin-key`,method:"GET",headers:{"X-Project-Id":this.adapterConfig.projectId},timeoutMs:Ic}),r=xc(t.data);if(!(r!=null&&r.keyVersion)||!(r!=null&&r.publicKey))throw new h(l.PIN_ENCRYPTION_FAILED,"pin-key 응답을 해석할 수 없습니다.");const n=Pc(r.publicKey),i=await e.importKey("spki",bc(n),{name:"RSA-OAEP",hash:"SHA-256"},!1,["encrypt"]);return{version:r.keyVersion,key:i}}}async function Rc(s,e){const t=Rn();if(!t)throw new h(l.PIN_ENCRYPTION_FAILED,"WebCrypto를 사용할 수 없어 PIN을 암호화할 수 없습니다.");const r=await t.encrypt({name:"RSA-OAEP"},s,new TextEncoder().encode(e));return new Uint8Array(r)}function Rn(){const s=globalThis.crypto;return(s==null?void 0:s.subtle)??null}function Oc(s){return Nc(s).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}const st="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";function Nc(s){let e="";for(let t=0;t<s.length;t+=3){const r=s[t],n=s[t+1],i=s[t+2];e+=st[r>>2],e+=st[(r&3)<<4|(n??0)>>4],e+=n===void 0?"=":st[(n&15)<<2|(i??0)>>6],e+=i===void 0?"=":st[i&63]}return e}function Pc(s){const e=s.replace(/-----BEGIN [A-Z ]+-----/g,"").replace(/-----END [A-Z ]+-----/g,"").replace(/\s+/g,"").replace(/-/g,"+").replace(/_/g,"/"),t=e.length%4===0?e:e+"=".repeat(4-e.length%4),r=[];for(let n=0;n<t.length;n+=4){const i=[0,1,2,3].map(a=>{const o=t[n+a];if(o==="="||o===void 0)return-1;const c=st.indexOf(o);if(c===-1)throw new h(l.PIN_ENCRYPTION_FAILED,"pin-key 공개키가 올바른 base64가 아닙니다.");return c});r.push((i[0]&63)<<2|(i[1]&63)>>4),i[2]!==-1&&r.push((i[1]&15)<<4|(i[2]&63)>>2),i[3]!==-1&&r.push((i[2]&3)<<6|i[3]&63)}return new Uint8Array(r)}function bc(s){const e=new Uint8Array(s.length);return e.set(s),e.buffer}function xc(s){if(!s||typeof s!="object")return null;const e=s;if(typeof e.code=="number"){if(e.code<0||e.code>=400)throw new h(l.PIN_ENCRYPTION_FAILED,`pin-key 조회 실패 (${e.code}): ${String(e.message??e.data??"")}`);const t=e.data;if(t&&typeof t=="object")return t}return typeof e.keyVersion=="string"&&typeof e.publicKey=="string"?e:null}const vc=3e4,Cc=1e3;class Dc{async request(e){const t=e.retries??0;for(let r=0;r<=t;r++){try{const n=await this._doRequest(e);if(n.status<500||r===t)return n}catch(n){if(r===t)throw n}await new Promise(n=>setTimeout(n,Cc*2**r))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const t=new AbortController,r=setTimeout(()=>t.abort(),e.timeoutMs??vc);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:t.signal,credentials:e.credentials});let i;const a=await n.text();try{i=a?JSON.parse(a):null}catch{i={_raw:a}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(r)}}}function kc(s){const e={raw:s},t=s.search(/(^|;)\s*info=/i),r=t>=0?s.slice(0,t):s;if(t>=0){const n=s.slice(t).replace(/^;?\s*info=/i,"").trim();n&&(e.infoUrl=n)}for(const n of r.split(";")){const[i,...a]=n.split("=");if((i==null?void 0:i.trim().toLowerCase())==="sunset"){const o=a.join("=").trim();o&&(e.sunset=o)}}return e}function On(s){try{return new URL(s).origin}catch{return null}}class Lc{constructor(e,t){this.inner=e,this.options=t}async request(e){if(!this.isGateway(e.url))return this.inner.request(e);const t=await this.inner.request(this.options.sendVersionHeader===!1?e:{...e,headers:{...e.headers,[Fn]:this.options.version}});return this.inspect(t),t}isGateway(e){const t=On(e);return t===null?!1:this.options.getGatewayBaseUrls().some(r=>On(r)===t)}inspect(e){var n,i,a,o;const t=Wc(e.headers,Hn);t&&((i=(n=this.options).onDeprecation)==null||i.call(n,kc(t)));const r=e.data;r&&r.code===ct&&((o=(a=this.options).onUnsupported)==null||o.call(a,{message:Uc(r)}))}}function Uc(s){for(const e of[s.data,s.message])if(typeof e=="string"&&e.trim())return e}function Wc(s,e){if(!s)return;const t=e.toLowerCase();for(const[r,n]of Object.entries(s))if(r.toLowerCase()===t&&n)return n}const Bc=[/CROSSx\/([\d.]+)/i,/ONE\s?wallet[^\s/]*\/([\d.]+)/i,/ONE\s?pocket[^\s/]*\/([\d.]+)/i];function yr(){return typeof window>"u"?void 0:window}function Mc(){const s=yr();return s==null?void 0:s.__crossx}function Fc(s){return s==="ios"||s==="android"?s:null}function Ar(){const s=typeof navigator>"u"?"":navigator.userAgent;return/Android/i.test(s)?"android":/iPhone|iPad|iPod|Macintosh/i.test(s)?"ios":null}function Kc(s,e){const t=a=>a.split(/[^\d]+/).filter(o=>o!=="").map(o=>Number.parseInt(o,10)),r=t(s),n=t(e),i=Math.max(r.length,n.length);for(let a=0;a<i;a+=1){const o=(r[a]??0)-(n[a]??0);if(o!==0)return o}return 0}function Hc(){const s=yr();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 Nn(){const s=typeof navigator>"u"?"":navigator.userAgent;for(const e of Bc){const t=e.exec(s);if(t)return t[1]??null}}function nt(){const s=Mc();if(s!=null&&s.browser)return{version:s.version??null,platform:Fc(s.platform)??Ar(),detectedBy:"marker"};if(Hc())return{version:Nn()??null,platform:Ar(),detectedBy:"bridge"};const e=Nn();return e!==void 0?{version:e,platform:Ar(),detectedBy:"user-agent"}:null}function Gc(){return nt()!==null}function $c(s=3e3){const e=nt();return e?Promise.resolve(e):yr()?new Promise(t=>{const r=Date.now(),n=setInterval(()=>{const i=nt();if(i){clearInterval(n),t(i);return}Date.now()-r>=s&&(clearInterval(n),t(null))},50)}):Promise.resolve(null)}const Vc=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"]),Jc="crossx://oauth-callback",qc="2.3.2";function Yc(s){return s.platform!=="ios"?!1:s.version?Kc(s.version,qc)<=0:!0}class De{constructor(){this.abortPending=null}cancelPending(e="외부 경로 인증으로 OAuth 대기를 중단했습니다"){const t=this.abortPending;t&&(d.log("[CROSSx] OAuth 대기 중단 —",e),t(e))}static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const t=e.split(".");if(t.length<2)throw new Error("Invalid JWT format");const r=(t[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(r);return JSON.parse(n)}static async sha256Hex(e){const t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,t){const r=De.parseJwtPayload(e),n=r.nonce,i=typeof r.iss=="string"?r.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:r.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(r)});return}if(i.includes("appleid.apple.com")){const a=await De.sha256Hex(t);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:a.length,receivedHashLength:n.length,match:n===a}),n!==a)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:t.length,receivedLength:n.length,match:n===t}),n!==t)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((t,r)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),a=window.screenX+(window.outerWidth-n)/2,o=window.screenY+(window.outerHeight-i)/2,c=De.generateRandom16Hex(),u=De.generateRandom16Hex(),f=nt();let g=e.authUrl;f&&e.legacyAuthUrl&&Yc(f)&&(g=e.legacyAuthUrl,d.info("[CROSSx] 구버전 iOS 지갑 감지 — 이관 전 OAuth 호스트 사용",{appVersion:f.version??"(unknown)",detectedBy:f.detectedBy,authUrlBase:e.legacyAuthUrl}));const S=g.includes("?")?"&":"?",E=encodeURIComponent(window.location.origin);let m=`${g}${S}state=${c}&nonce=${u}&origin=${E}`;f&&!m.includes("redirectUrl=")&&(m+=`&redirectUrl=${encodeURIComponent(Jc)}`,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:u.length,authUrlBase:g});const y=window.open(m,f?"_blank":"CROSSx OAuth",`width=${n},height=${i},left=${a},top=${o}`);if(!y){r(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const w=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),H(),r(new Error("Authentication timeout"))},300*1e3),A=10,P=30;let F=0,M=null;const V=()=>{clearInterval(U),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+P+"초간 대기합니다"),M=setTimeout(()=>{H(),r(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},P*1e3)},U=setInterval(()=>{F++;try{if(!y.closed)return;if(!!f){H(),r(new h(l.USER_REJECTED,"로그인이 취소되었습니다"));return}const ee=typeof document<"u"&&document.hasFocus();F<=A&&!ee?V():(H(),r(new h(l.USER_REJECTED,"로그인이 취소되었습니다")))}catch{V()}},1e3),H=()=>{this.abortPending=null,clearTimeout(w),clearInterval(U),M&&clearTimeout(M),window.removeEventListener("message",Z)},Z=v=>{if(!Vc.has(v.origin))return;H();const ee=typeof v.data.status=="string",B=ee?v.data.data??{}:v.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:ee?"wrapped":"flat",status:ee?v.data.status:"(flat)"});const K=(B==null?void 0:B.state)??v.data.state;if(!K||K!==c){r(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ee&&v.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",B==null?void 0:B.error),r(new Error((B==null?void 0:B.error)||"Authentication failed"));return}if(!ee&&(B!=null&&B.error)){d.error("[CROSSx] OAuth 실패:",B.error),r(new Error(B.error||"Authentication failed"));return}const k=B==null?void 0:B.idToken,_=B==null?void 0:B.accessToken,p=_??k,I=(B==null?void 0:B.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!_,hasIdToken:!!k,hasEmail:!!I}),!p){d.error("[CROSSx] 토큰을 찾을 수 없음:",v.data),r(new Error("Token not found in response"));return}const R={token:p,email:I},b=N=>{De.verifyIdTokenNonce(N,u).then(()=>t(R)).catch(x=>{d.error("[CROSSx] nonce 검증 실패:",x),r(x instanceof Error?x:new Error("nonce verification failed"))})};_?_.split(".").length===3?b(_):k?b(k):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),t(R)):k?b(k):r(new Error("Token not found in response"))};this.abortPending=v=>{H(),r(new Error(v))},window.addEventListener("message",Z)})}}const it="crossx_wallet_data",ze="crossx_mock_pin_hash";class zc{constructor(e,t){this.storage=e,this.pinStore=t??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const t=await this.storage.get(it)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${t}`),t}async getOrCreateWallet(e){var t;try{const r=await this.storage.get(it);if(r)return r;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(it,n);const i=(t=this.pinStore)==null?void 0:t.get();return i&&(await this.storage.set(ze,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(r){throw new h(l.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",r)}}async getAddresses(e){const t=await this.storage.get(it);return t?[{address:t.address,index:0}]:[]}async getAddress(e,t){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${t}`}}async prepare(e,t){const r="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${r}`),{uuid:r,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,t,r,n=0,i,a){return d.log(`[Mock] signMessage chainId=${t} index=${n} uuid=${i} from=${a}: "${r}"`),{chainId:t,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,t,r,n=0,i,a){return d.log(`[Mock] signTypedData chainId=${t} index=${n} uuid=${i} from=${a}`),{chainId:t,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,t,r,n=0,i){d.log(`[Mock] signTransaction chainId=${t} index=${n} uuid=${i}:`,r);const a="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:t,signature:this.generateMockSignature(),txHash:a,format:"hex"}}async sendTransaction(e,t,r,n){return d.log(`[Mock] sendTransaction chainId=${t} uuid=${n}:`,r),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var r;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const t=await this.storage.get(ze);return t&&t!==e?!1:(t||await this.storage.set(ze,e),(r=this.pinStore)==null||r.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,t){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new h(l.PIN_WRONG,"Incorrect PIN.");const r=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(ze);if(n&&r&&n!==r)throw new h(l.PIN_WRONG,"Incorrect PIN.");await this.storage.set(ze,t),d.log("[Mock] changePin 완료")}async migrateWallet(e,t){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${t}`),this.migrateScenario==="wrong_pin")throw new h(l.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 o={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new h(l.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",o)}const r={id:t,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(it,r);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(ze,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),r}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,t){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}const Xc=["password","newPassword","recoveryPin"];class ke{constructor(e,t,r,n,i,a){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=t,this.transport=r,this.tokenStore=n,this.pinStore=i??null,this.pinEncryptor=a??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(Nr))return e;const t=!e||this.tokenStore.isExpiringSoon(Nr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(t)throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async sealPinFields(e){if(!this.pinEncryptor||!e||typeof e!="object")return e;let t=null;for(const r of Xc){const n=e[r];if(typeof n!="string"||n==="")continue;const i=await this.pinEncryptor.seal(n);i!==n&&(t||(t={...e}),t[r]=i)}return t??e}async request(e,t,r,n=!1,i=!1){var f,g,S,E;const a=await this.ensureValidToken(),o=`${this.baseUrl}${t}`,c={Authorization:`Bearer ${a}`,"Content-Type":"application/json","X-Project-Id":this.projectId},u=await this.sealPinFields(r);try{const y=(await this.transport.request({url:o,method:e,headers:c,body:u??void 0})).data;if(y&&typeof y.code=="number"){if(y.code<0||y.code>=400){const w=y.message||y.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:y.code,message:w,url:o,method:e});const A=ke.mapGatewayError(y.code,y.data);if(A===l.PIN_ENCRYPTION_INVALID&&this.pinEncryptor&&(this.pinEncryptor.requireEncryption(),this.pinEncryptor.invalidate(),!i))return d.warn("[CROSSx] Gateway -10045 감지 — pin-key 재조회 후 재시도"),this.request(e,t,r,n,!0);if(A===l.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,t,r,!0,i);throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(A===l.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(f=this._onUnauthorized)==null||f.call(this),new h(l.USER_NOT_FOUND,ke.getGatewayErrorMessage(y.code,w));const P=A===l.AUTH_NOT_AUTHENTICATED?l.SESSION_EXPIRED:A,F=P===l.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":ke.getGatewayErrorMessage(y.code,w),M=y.data;let V;throw A===l.PIN_LOCKED?V=ke.extractLockDetails(M):A===l.ADDRESS_LIMIT_EXCEEDED?V={limit:kt,raw:M}:V=M??void 0,new h(P,F,V)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:y.code,url:o,method:e}),y.data??y}return y}catch(m){if(m instanceof h)throw m;const y=((g=m.response)==null?void 0:g.status)??m.status;if((y===401||y===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${y} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,t,r,!0,i);throw new h(l.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((S=m.response)!=null&&S.data){const w=m.response.data,A=w.message||w.data||"API 요청에 실패했습니다",P=w.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:P,message:A,url:o,method:e,status:(E=m.response)==null?void 0:E.status}),new h(l.UNKNOWN_ERROR,`Wallet Gateway 오류 (${P}): ${A}`)}throw m}}async checkWallet(){var t,r;d.log("[CROSSx] GET /mnemonic/check"),(r=(t=this.pinEncryptor)==null?void 0:t.prewarm)==null||r.call(t);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 t;if(this._walletStatusCache!==null?(t=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",t)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),t=await this.checkWallet(),this._walletStatusCache=null),t==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new h(l.MIGRATION_BACKUP_EXISTS,"기존 지갑 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(t==="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 r={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",r);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(r=>({address:r.address,index:r.index,name:r.name}))}async getAddress(e,t){const r={password:this.requirePin(),index:t};return{address:(await this.request("POST","/mnemonic/address",r)).address,derivationPath:`m/44'/60'/0'/0/${t}`}}async prepare(e,t){let r;switch(e){case"sign":case"send":if(!t.tx)throw new h(l.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");r={unsignedTx:this.buildUnsignedTx(t.tx)};break;case"sign-message":if(!t.message)throw new h(l.TX_INVALID_PARAMS,"prepare: message가 필요합니다");r={message:t.message},t.from&&(r.from=t.from);break;case"sign-typed-data":if(!t.typedData)throw new h(l.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");r={typedData:t.typedData},t.from&&(r.from=t.from);break}const n={action:e,params:r},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,t,r,n,i,a){const o={message:r,password:this.requirePin()};i&&(o.uuid=i),a&&(o.from=a);const c=await this.request("POST","/mnemonic/sign-message",o);return{chainId:t,signature:c.signature,format:"hex"}}async signTypedData(e,t,r,n,i,a){const o={typedData:r,password:this.requirePin()};i&&(o.uuid=i),a&&(o.from=a);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(t)}`,o);return{chainId:t,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,t,r,n,i){const a={unsignedTx:this.buildUnsignedTx(r),password:this.requirePin()};i&&(a.uuid=i);const o=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(t)}`,a);return{chainId:t,signature:o.signedTx,txHash:o.txHash,format:"hex"}}async sendTransaction(e,t,r,n){const i={unsignedTx:this.buildUnsignedTx(r),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(t)}`,i)).txHash}}async migrateWallet(e,t){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const r={recoveryPin:e,sub:t,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",r);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:t,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const t={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",t)}async verifyPin(e){const t={password:e},r=await this.request("POST","/mnemonic/verify-password",t);if(!r.valid&&r.passwordStatus){const n=r.passwordStatus;if(n.permanent)throw new h(l.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new h(l.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new h(l.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return r.valid}async changePin(e,t){const r={password:this.requirePin(),newPassword:t};await this.request("POST","/mnemonic/change-password",r)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,t){const r={recoveryPin:e,sub:t};return this.request("POST","/mnemonic/verify-recovery-pin",r)}requirePin(){const e=this.getPin();if(!e)throw new h(l.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const t=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,r={},n=(t==null?void 0:t.lockExpiresAt)??(t==null?void 0:t.lock_expires_at);n&&(r.lockExpiresAt=n>1e10?n:n*1e3);const i=(t==null?void 0:t.remainingAttempts)??(t==null?void 0:t.remaining_attempts);typeof i=="number"&&(r.remainingAttempts=i);const a=(t==null?void 0:t.maxAttempts)??(t==null?void 0:t.max_attempts);return typeof a=="number"&&(r.maxAttempts=a),typeof(t==null?void 0:t.permanent)=="boolean"&&(r.permanent=t.permanent),r}static hasLockInfo(e){const t=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!t||typeof t!="object"?!1:typeof t.remainingAttempts=="number"||typeof t.remaining_attempts=="number"||typeof t.maxAttempts=="number"||typeof t.max_attempts=="number"}static mapGatewayError(e,t){switch(e){case-10002:return l.AUTH_NOT_AUTHENTICATED;case-10001:return l.UNKNOWN_ERROR;case-10006:return l.GATEWAY_INTERNAL_ERROR;case-10007:return l.BROADCAST_FAILED;case-10008:return l.GATEWAY_LOCK_CONFLICT;case-10004:return l.WALLET_ALREADY_EXISTS;case-10005:return l.WALLET_NOT_FOUND;case-10011:return l.WALLET_NOT_FOUND;case-10030:return l.WALLET_INCONSISTENT_STATE;case-10010:return l.MIGRATION_FAILED;case-10012:return l.MIGRATION_BACKUP_EXISTS;case-10013:return l.WITHDRAW_FAILED;case-10033:return l.USER_NOT_FOUND;case-10036:return l.ADDRESS_LIMIT_EXCEEDED;case-10027:return l.MIGRATION_PIN_LOCKED;case-10022:return l.PROJECT_NOT_REGISTERED;case-10023:return l.PROJECT_ID_MISSING;case-10024:return l.ORIGIN_NOT_ALLOWED;case-10025:return l.INVALID_APP_TYPE;case ct:return l.SDK_VERSION_UNSUPPORTED;case-10028:return ke.hasLockInfo(t)?l.PIN_LOCKED:l.PIN_WRONG;case-10029:return l.PIN_INVALID;case-10031:return l.PIN_LOCKED;case-10032:return l.PIN_REPEATED_PATTERN;case-10045:return l.PIN_ENCRYPTION_INVALID;case-10046:return l.PIN_POLICY_VIOLATION;case-10026:return l.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return l.PREPARE_FAILED;case-10016:return l.PREPARE_EXPIRED;case-10017:case-10018:return l.PREPARE_MISMATCH;case-10020:return l.CHAIN_NOT_SUPPORTED;case-10021:return l.INVALID_CHAIN;case-10040:return l.HMAC_REQUIRED;case-10041:return l.HMAC_VERIFICATION_FAILED;default:return l.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,t){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 (${t}). 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 ct:return`This SDK version is no longer supported. Update @nexus-cross/crossx-sdk-core.${t?` (${t})`:""}`;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 ${kt} accounts allowed.`;case-10045:return"Could not securely send your PIN. Please try again.";case-10046:return t||"This PIN does not meet the security policy. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${t}`}}}class jc{constructor(e,t,r,n=()=>{},i=()=>{},a=()=>{}){this.inner=e,this.getBridge=t,this.isAuthenticatedViaRNBridge=r,this.assertBridgeSessionActive=n,this.getAppName=i,this.onBridgeUnauthorized=a,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(o,c)=>e.prepare(o,c)),e.migrateWallet&&(this.migrateWallet=(o,c)=>e.migrateWallet(o,c)),e.verifyPin&&(this.verifyPin=o=>e.verifyPin(o)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(o,c)=>e.verifyRecoveryPin(o,c))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async innerOwnsAddress(e,t){if(!t)return!0;try{return(await this.inner.getAddresses(e)).some(n=>n.address.toLowerCase()===t.toLowerCase())}catch{return!1}}async recoverFromUnauthorized(e,t,r,n){return!vr(e)||!await this.innerOwnsAddress(t,r)?!1:(this.onBridgeUnauthorized(`native 가 ${n} 을 ERR_BRIDGE_NOT_AUTHORIZED 로 거부 — inner provider 로 폴백`),!0)}async signMessage(e,t,r,n,i,a){const o=this.shouldUseBridge();if(o!=null&&o.signMessage){this.assertBridgeSessionActive();try{const c=await o.signMessage({chainId:t,message:r,from:a,index:n,dappName:this.getAppName()});return{chainId:t,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,a,"signMessage"))throw Ue(c,l.SIGNATURE_FAILED)}}return this.inner.signMessage(e,t,r,n,i,a)}async signTypedData(e,t,r,n,i,a){const o=this.shouldUseBridge();if(o!=null&&o.signTypedData){this.assertBridgeSessionActive();try{const c=await o.signTypedData({chainId:t,typedData:r,from:a,index:n,dappName:this.getAppName()});return{chainId:t,signature:c.signature,format:"hex"}}catch(c){if(!await this.recoverFromUnauthorized(c,e,a,"signTypedData"))throw Ue(c,l.SIGNATURE_FAILED)}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,t,r,n,i,a)}async signTransaction(e,t,r,n,i){const a=this.shouldUseBridge();if(a!=null&&a.signTransaction){this.assertBridgeSessionActive();try{const o=await a.signTransaction({chainId:t,tx:this.toBridgeTx(r),from:r.from,index:n,dappName:this.getAppName()});return{chainId:t,signature:o.signedTx,format:"hex"}}catch(o){if(!await this.recoverFromUnauthorized(o,e,r.from,"signTransaction"))throw Ue(o,l.SIGNATURE_FAILED)}}return this.inner.signTransaction(e,t,r,n,i)}async sendTransaction(e,t,r,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction){this.assertBridgeSessionActive();try{return{txHash:(await i.sendTransaction({chainId:t,tx:this.toBridgeTx(r),from:r.from,dappName:this.getAppName()})).txHash}}catch(a){if(!await this.recoverFromUnauthorized(a,e,r.from,"sendTransaction"))throw Ue(a,l.TRANSACTION_FAILED)}}if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,t,r,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,t){return this.inner.getAddress(e,t)}setOnUnauthorized(e){var t,r;(r=(t=this.inner).setOnUnauthorized)==null||r.call(t,e)}setTokenRefresher(e){var t,r;(r=(t=this.inner).setTokenRefresher)==null||r.call(t,e)}}class at{constructor(e,t){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=t}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 t=e.data.chains;return this.populateCache(t,!1),t}catch{const e=at.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const r=(await this.getChains()).find(n=>n.chainId===e);return r||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?Bn:Wn;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,t){this.cache.clear();for(const r of e)this.cache.set(r.chainId,r);this.loadedAt=Date.now(),this.usingFallback=t}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 t=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new h(at.mapErrorCode(e.code),t)}}fallbackOrThrow(e){const t=at.fallbackChains().find(r=>r.chainId===e);if(t)return t;throw new h(l.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(lt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return l.CHAIN_NOT_SUPPORTED;case-10021:return l.INVALID_CHAIN;case-10022:return l.PROJECT_NOT_REGISTERED;case-10023:return l.PROJECT_ID_MISSING;case-10024:return l.APP_IDENTIFIER_MISSING;case-10025:return l.INVALID_APP_TYPE;case ct:return l.SDK_VERSION_UNSUPPORTED;default:return l.UNKNOWN_ERROR}}}function Le(s){return Promise.reject(new h(l.UI_NOT_PROVIDED,`[CROSSx] "${s}" needs a UI adapter. Create the SDK with createCROSSxSDKWithOverrides(config, { ui }) from @nexus-cross/crossx-sdk-core/internal.`))}class Zc{requestConfirmation(e){return Le("requestConfirmation")}showLoginSelector(){return Le("showLoginSelector")}showMigrationFoundPrompt(){return Le("showMigrationFoundPrompt")}showRecoveryPinInputPrompt(){return Le("showRecoveryPinInputPrompt")}showWalletSelector(){return Le("showWalletSelector")}showPinSetupPrompt(){return Le("showPinSetupPrompt")}showPinInputPrompt(){return Le("showPinInputPrompt")}async showSessionAlert(){return"signout"}async showTransactionComplete(e){}async showTransactionProgress(e,t){try{await t}catch{}}async showRecoveryPinLockedPrompt(e,t){}async showUpdateRequired(){}setTheme(){}setMessages(){}setPinKeyboard(){}}class Qc{constructor(e,t,r,n=()=>!1){this.browserConfirmation=e,this.getBridge=t,this.getOrigin=r,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 t=this.getBridge();if(!t)return{approved:!1,reason:"Bridge not available"};const{operation:r,payload:n,chainId:i}=this.mapToNativeParams(e),a={operation:r,payload:n,dappOrigin:this.getOrigin(),chainId:i};return await t.requestUserConfirmation(a)}mapToNativeParams(e){const t=e.type;switch(t){case"sign-message":{const r=e;return{operation:"signMessage",payload:{message:r.message,from:r.from,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}case"sign-typed-data":{const r=e;return{operation:"signTypedData",payload:{typedData:r.typedData,from:r.from,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}case"sign":{const r=e;return{operation:"signTransaction",payload:{from:r.from,to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nativeSymbol:r.nativeSymbol,nativeDecimals:r.nativeDecimals,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}case"send":{const r=e;return{operation:"sendTransaction",payload:{from:r.from,to:r.to,value:r.value,data:r.data,gasLimit:r.gasLimit,gasPrice:r.gasPrice,maxFeePerGas:r.maxFeePerGas,maxPriorityFeePerGas:r.maxPriorityFeePerGas,nativeSymbol:r.nativeSymbol,nativeDecimals:r.nativeDecimals,dappName:r.dappName,accountName:r.accountName},chainId:r.chainId}}default:throw new h(l.INVALID_CONFIG,`Unknown confirmation type: ${String(t)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,t){if(this.shouldDelegateToBridge()){try{await t}catch{}return}return this.browserConfirmation.showTransactionProgress(e,t)}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,t){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,t)}async showWalletSelector(e,t,r,n){const i=this.getBridge();if(this.shouldDelegateToBridge()&&(i!=null&&i.showWalletSelector))try{const a=await i.showWalletSelector({requiredAddress:r}),o=e.find(c=>c.address.toLowerCase()===a.address.toLowerCase());return{address:a.address,index:(o==null?void 0:o.index)??a.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,t,r,n)}async showWalletCreatedPrompt(){var e,t;if(!this.shouldDelegateToBridge())return((t=(e=this.browserConfirmation).showWalletCreatedPrompt)==null?void 0:t.call(e))??Promise.resolve()}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}showUpdateRequired(e){return this.browserConfirmation.showUpdateRequired(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,t){return this.browserConfirmation.setTheme(e,t)}setMessages(e){return this.browserConfirmation.setMessages(e)}setPinKeyboard(e){var t,r;(r=(t=this.browserConfirmation).setPinKeyboard)==null||r.call(t,e)}}class Pn{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const t=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof t.exp=="number"?t.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}const el=new WeakMap;function tl(s,e){el.set(s,e)}function bn(s){return rl(s)}function rl(s,e){var Z;if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
3264
8
  Set the projectId field in SDKConfig when calling createCROSSxSDK().
3265
- Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=Ke.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,legacyOauthServiceUrl:r.legacyOauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&ns.isAvailable();!i&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new ns(s.projectId):new Xi,a=new qa;let c=null;const l=new oc(new nc,{version:ut,sendVersionHeader:Yn,getGatewayBaseUrls:()=>[n.gatewayUrl],onDeprecation:q=>c==null?void 0:c.handleSdkVersionDeprecation(q),onUnsupported:q=>c==null?void 0:c.handleSdkVersionUnsupported(q)}),d=new $e,p=new $n,f=new Wt,g=new ja(n,l);let w;s.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),w=new mc(o,f)):(u.log("[CROSSx] Remote Wallet Provider 사용"),w=new Ue(n,o,l,p,f,g));const m=()=>{var q;return((q=c==null?void 0:c.isAuthenticatedViaRNBridge)==null?void 0:q.call(c))??!1},x=()=>{var q;return(q=c==null?void 0:c.assertRNBridgeSessionActive)==null?void 0:q.call(c)},S=q=>{var z;(z=c==null?void 0:c.clearRNBridgeDelegation)==null||z.call(c,q)};w=new bc(w,()=>{var q;return(q=c==null?void 0:c.getRNBridge)==null?void 0:q.call(c)},m,x,()=>s.appName,S);const I=new lt(n,l),U=new Tl(s.theme??"light",s.themeTokens,s.displayDecimals,s.pinKeyboard),L=new Rl(U,()=>{var q;return(q=c==null?void 0:c.getRNBridge)==null?void 0:q.call(c)},()=>typeof window<"u"?window.location.origin:"http://localhost",m),H=new tt(t,n,o,a,l,d,w,p,L,I,f,g,new vi);c=H,Cl(H,{transport:l,storage:o,walletProvider:w,confirmation:L,tokenStore:p,pinStore:f,adapterConfig:n,pinEncryptor:g});const G=H.signInUseCase;return G&&typeof G.setFreshTokenCallback=="function"&&G.setFreshTokenCallback(()=>H.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=H),H}const kl=Un;function Pl(s){const e=Dl(s),r=Ll(e),t=JSON.parse(r);Ml(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Dl(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function Ll(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=Bl(s);return decodeURIComponent(e)}function Bl(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Ml(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return X.CONNECT_OTHER_WALLET_DISPLAY_ORDER=Mr,X.CROSSxError=_,X.CROSSxEthereumProvider=Ut,X.CROSSxSDK=tt,X.ChainId=si,X.ConnectOtherWalletItem=We,X.ErrorCode=h,X.MNEMONIC_ADDRESS_LIMIT=dt,X.ONEpocketError=_,X.ONEpocketEthereumProvider=Ut,X.ONEpocketSDK=tt,X.PinMemoryStore=Wt,X.TokenMemoryStore=$n,X.WALLET_BRAND_NAME=pt,X.createCROSSxSDK=Un,X.createONEpocketSDK=kl,X.getConnectOtherWalletLabel=$r,X.getWalletBrowserInfo=at,X.isWalletInAppBrowser=pc,X.parseOAuthDeeplink=Pl,X.waitForWalletBrowser=_c,Object.defineProperty(X,Symbol.toStringTag,{value:"Module"}),X})({});
9
+ Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);if(s.walletServer==="one-wallet"&&!((Z=s.oneId)!=null&&Z.clientId))throw new Error("[CROSSx] Fatal: walletServer 'one-wallet' requires SDKConfig.oneId (ONE ID login) — DEV2TF-2755");s.debug;const t=Me.production,r={...s,oauthServiceUrl:t.oauthServiceUrl,legacyOauthServiceUrl:t.legacyOauthServiceUrl,authApiUrl:t.authApiUrl,walletGatewayUrl:t.walletGatewayUrl,pinReuse:e==null?void 0:e.pinReuse},n={gatewayUrl:t.walletGatewayUrl,projectId:s.projectId},i=r.authMode!=="cookie"&&ls.isAvailable();!i&&r.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),r.secureStorageAvailable=i;const a=i?new ls(s.projectId):new Oa,o=new yc;let c=null;const u=new Lc(new Dc,{version:ot,sendVersionHeader:Kn,getGatewayBaseUrls:()=>[n.gatewayUrl],onDeprecation:v=>c==null?void 0:c.handleSdkVersionDeprecation(v),onUnsupported:v=>c==null?void 0:c.handleSdkVersionUnsupported(v)}),f=new De,g=new Pn,S=new Mt,E=new Tc(n,u);let m;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),m=new zc(a,S)):s.walletServer==="one-wallet"?(d.log("[CROSSx] one-wallet-api Wallet Provider 사용"),m=new is({baseUrl:()=>_t().oneWalletApiUrl,transport:u,pinStore:S,getAccessToken:()=>c?c.getOneIdAccessToken():Promise.reject(new h(l.AUTH_NOT_INITIALIZED,"SDK가 아직 만들어지지 않았습니다"))})):(d.log("[CROSSx] Remote Wallet Provider 사용"),m=new ke(n,a,u,g,S,E));const y=()=>{var v;return((v=c==null?void 0:c.isAuthenticatedViaRNBridge)==null?void 0:v.call(c))??!1},w=()=>{var v;return(v=c==null?void 0:c.assertRNBridgeSessionActive)==null?void 0:v.call(c)},A=v=>{var ee;(ee=c==null?void 0:c.clearRNBridgeDelegation)==null||ee.call(c,v)};s.walletServer!=="one-wallet"&&(m=new jc(m,()=>{var v;return(v=c==null?void 0:c.getRNBridge)==null?void 0:v.call(c)},y,w,()=>s.appName,A));const P=new at(n,u);_t();const F=new Zc,V=new Qc(F,()=>{var v;return(v=c==null?void 0:c.getRNBridge)==null?void 0:v.call(c)},()=>typeof window<"u"?window.location.origin:"http://localhost",y),U=new Ze(r,n,a,o,u,f,m,g,V,P,S,E,new gi);c=U,tl(U,{transport:u,storage:a,walletProvider:m,confirmation:V,tokenStore:g,pinStore:S,adapterConfig:n,pinEncryptor:E});const H=U.signInUseCase;return H&&typeof H.setFreshTokenCallback=="function"&&H.setFreshTokenCallback(()=>U.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=U),U}const sl=bn;function nl(s){const e=il(s),t=al(e),r=JSON.parse(t);cl(r);const{data:n}=r;return{status:r.status,state:r.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:r}}function il(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),t=e.searchParams.get("crossx_oauth_result");if(t)return t;const r=e.searchParams.get("data");if(r)return r;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function al(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=ol(s);return decodeURIComponent(e)}function ol(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 cl(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 t=e.data;if(typeof t.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof t.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return W.CONNECT_OTHER_WALLET_DISPLAY_ORDER=xr,W.CROSSxError=h,W.CROSSxEthereumProvider=Ut,W.CROSSxSDK=Ze,W.ChainId=zn,W.ConnectOtherWalletItem=br,W.ErrorCode=l,W.MESSAGES_EN=Wt,W.MESSAGES_KO=kr,W.MNEMONIC_ADDRESS_LIMIT=kt,W.ONEpocketError=h,W.ONEpocketEthereumProvider=Ut,W.ONEpocketSDK=Ze,W.PinMemoryStore=Mt,W.TokenMemoryStore=Pn,W.WALLET_BRAND_NAME=Lt,W.WEI_DISPLAY_DECIMALS=Dt,W.createCROSSxSDK=bn,W.createONEpocketSDK=sl,W.getConnectOtherWalletLabel=$n,W.getWalletBrowserInfo=nt,W.isWalletInAppBrowser=Gc,W.parseOAuthDeeplink=nl,W.waitForWalletBrowser=$c,Object.defineProperty(W,Symbol.toStringTag,{value:"Module"}),W})({});