@nexus-cross/crossx-sdk-core 2.2.0-beta.1 → 2.2.0-beta.10

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 (31) hide show
  1. package/dist/__tests__/adapters/BrowserConfirmationAdapter.test.d.ts +2 -0
  2. package/dist/__tests__/adapters/BrowserConfirmationAdapter.test.d.ts.map +1 -0
  3. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +16 -1
  4. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
  5. package/dist/core/i18n/index.d.ts +10 -0
  6. package/dist/core/i18n/index.d.ts.map +1 -1
  7. package/dist/core/i18n/messages.en.d.ts.map +1 -1
  8. package/dist/core/i18n/messages.ko.d.ts.map +1 -1
  9. package/dist/core/i18n/types.d.ts +101 -55
  10. package/dist/core/i18n/types.d.ts.map +1 -1
  11. package/dist/core/services/RNBridgeBootstrapService.d.ts.map +1 -1
  12. package/dist/core/types/events.d.ts +2 -0
  13. package/dist/core/types/events.d.ts.map +1 -1
  14. package/dist/core/types/index.d.ts +11 -0
  15. package/dist/core/types/index.d.ts.map +1 -1
  16. package/dist/core/types/rn-bridge.d.ts +2 -0
  17. package/dist/core/types/rn-bridge.d.ts.map +1 -1
  18. package/dist/core/usecases/SignInUseCase.d.ts +3 -1
  19. package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
  20. package/dist/crossx.global +199 -160
  21. package/dist/index.cjs +223 -184
  22. package/dist/index.js +2983 -2770
  23. package/dist/sdk/CROSSxSDK.d.ts +7 -0
  24. package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
  25. package/dist/sdk/factory.d.ts.map +1 -1
  26. package/dist/sdk/services/StateManager.d.ts +4 -1
  27. package/dist/sdk/services/StateManager.d.ts.map +1 -1
  28. package/dist/sdk/services/WalletLifecycleService.d.ts.map +1 -1
  29. package/dist/sdk/utils/amount.d.ts +2 -2
  30. package/dist/sdk/utils/amount.d.ts.map +1 -1
  31. package/package.json +1 -1
@@ -1,12 +1,13 @@
1
- var CROSSx=function(z){"use strict";var za=Object.defineProperty;var Ja=(z,h,_)=>h in z?za(z,h,{enumerable:!0,configurable:!0,writable:!0,value:_}):z[h]=_;var C=(z,h,_)=>Ja(z,typeof h!="symbol"?h+"":h,_);var Et,Qr;var h=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",r.SESSION_EXPIRED="SESSION_EXPIRED",r.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",r.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.BROADCAST_FAILED="BROADCAST_FAILED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",r.PIN_CANCELLED="PIN_CANCELLED",r.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",r.PIN_LOCKED="PIN_LOCKED",r.HMAC_REQUIRED="HMAC_REQUIRED",r.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",r.WITHDRAW_FAILED="WITHDRAW_FAILED",r.USER_NOT_FOUND="USER_NOT_FOUND",r.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",r.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",r.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(h||{});class _ extends Error{constructor(e,s,t){super(s),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}}}var We=(r=>(r.MetaMask="io.metamask",r.Binance="com.binance.wallet",r.CROSSx="crossx",r))(We||{});const sn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},as=["crossx","io.metamask","com.binance.wallet"];function cs(r){return sn[r]??r}function rn(r){return Array.isArray(r.connectOtherWallets)&&r.connectOtherWallets.length>0?[...r.connectOtherWallets]:r.showConnectOtherWallets===!0?[...as]:[]}const nt={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},nn=Object.fromEntries(Object.entries(nt).map(([r,e])=>[r,e.caipId])),on=new Map(Object.values(nt).map(r=>[r.caipId,r]));new Map(Object.values(nt).map(r=>[r.chainId,r]));const an={symbol:"",decimals:18};function At(r){var e;return((e=on.get(r))==null?void 0:e.nativeCurrency)??an}class ls{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){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(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[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,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[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 Ya(r){}function ds(r){ye=r}const d={info(...r){if(ye){ye.log(...r);return}console.log(...r)},log(...r){if(ye){ye.log(...r);return}},warn(...r){if(ye){ye.warn(...r);return}},error(...r){if(ye){ye.error(...r);return}}},cn={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:" PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:" PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",pinLocked_failureWarning:"추가 실패 시 계정이 잠금됩니다.",pinLocked_permanent:"너무 많은 시도 실패로 계정이 영구 잠금되었습니다.",alert_sessionExpired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_accountWithdrawn:"계정이 탈퇴 처리되었거나 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_walletNotFound:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_differentAccount:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
1
+ var CROSSx=function(z){"use strict";var Xa=Object.defineProperty;var Za=(z,h,_)=>h in z?Xa(z,h,{enumerable:!0,configurable:!0,writable:!0,value:_}):z[h]=_;var N=(z,h,_)=>Za(z,typeof h!="symbol"?h+"":h,_);var At,tn;var h=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.ADDRESS_LIMIT_EXCEEDED="ADDRESS_LIMIT_EXCEEDED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.RN_BRIDGE_NOT_AVAILABLE="RN_BRIDGE_NOT_AVAILABLE",s.RN_BRIDGE_HANDSHAKE_FAILED="RN_BRIDGE_HANDSHAKE_FAILED",s.RN_NATIVE_SESSION_EXPIRED="RN_NATIVE_SESSION_EXPIRED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(h||{});class _ 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}}}var We=(s=>(s.MetaMask="io.metamask",s.Binance="com.binance.wallet",s.CROSSx="crossx",s))(We||{});const nn={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},dr=["crossx","io.metamask","com.binance.wallet"];function ur(s){return nn[s]??s}function on(s){return Array.isArray(s.connectOtherWallets)&&s.connectOtherWallets.length>0?[...s.connectOtherWallets]:s.showConnectOtherWallets===!0?[...dr]:[]}const nt={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},an=Object.fromEntries(Object.entries(nt).map(([s,e])=>[s,e.caipId])),cn=new Map(Object.values(nt).map(s=>[s.caipId,s]));new Map(Object.values(nt).map(s=>[s.chainId,s]));const ln={symbol:"",decimals:18};function It(s){var e;return((e=cn.get(s))==null?void 0:e.nativeCurrency)??ln}class hr{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 Qa(s){}function pr(s){ye=s}const d={info(...s){if(ye){ye.log(...s);return}console.log(...s)},log(...s){if(ye){ye.log(...s);return}},warn(...s){if(ye){ye.warn(...s);return}},error(...s){if(ye){ye.error(...s);return}}},dn={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:"승인",tx_pending:"트랜잭션을 처리하고 있습니다...",tx_success:"트랜잭션 완료",tx_failed:"트랜잭션 실패",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",tx_progress_waiting_title:"확인 대기 ",tx_progress_waiting_text:"트랜잭션 영수증을 기다리는 중...",tx_complete_done_button:"모두 완료",label_to:"받는 주소",label_from:"보내는 주소",label_network:"네트워크",label_value:"금액",label_estimated_fee:"예상 수수료",label_est_tx_fee:"예상 수수료",label_max_priority_fee:"최대 우선 수수료",label_max_gas_fee:"최대 가스 수수료",label_gas_price:"가스 가격",label_gas_limit:"가스 한도",label_transfer:"전송량",label_tx_fee:"수수료",label_tx_hash:"Tx 해시",label_total:"합계",label_including_fees:"(수수료 포함)",label_primary_type:"Primary Type",login_selector_title:"로그인 방법 선택",login_selector_subtitle:"소셜 계정으로 간편하게 로그인하세요",login_selector_google:"Google로 로그인",login_selector_apple:"Apple로 로그인",login_selector_or:"또는",login_selector_terms_template:"계속 진행하면 NEXUS {tos}에 동의하고 {pp}에 동의하게 됩니다.",login_selector_terms_tos:"이용약관",login_selector_terms_pp:"개인정보 처리방침",login_selector_connect_other_wallets:"다른 지갑으로 연결",login_selector_connect_other_wallets_desc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_found_title:"소셜 계정에서 지갑 발견",migration_found_description:`소셜 계정에 연결된 지갑을 발견했습니다.
2
+ 4자리 PIN을 입력하여 자산을 복원하세요.`,migration_recover_button:"내 지갑 복구",migration_skip_button:"나중에 하기",recovery_pin_input_title:"내 지갑 복구",recovery_pin_input_placeholder:"지갑 복구를 위해 4자리 PIN을 입력하세요.",recovery_pin_input_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",wallet_selector_title:"연결된 지갑 선택",wallet_selector_description:"이전에 이 게임에서 사용한 지갑을 선택해 주세요.",wallet_selector_info_title:"왜 지갑을 선택해야 하나요?",wallet_selector_info_desc:"이전에 연결된 지갑을 확인하면 기존 데이터와 자산이 올바르게 동기화됩니다.",wallet_selector_add_button:"지갑 추가",wallet_selector_selected:"선택됨",wallet_selector_add_error_limit_exceeded:"계정 한도에 도달했습니다. 최대 {limit}개의 계정을 사용할 수 있습니다.",wallet_selector_add_error_generic:"새 계정을 추가하지 못했습니다. 다시 시도해 주세요.",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:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
2
3
 
3
- 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},us={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Please sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_walletNotFound:"Wallet data could not be found. Please sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
4
+ 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,session_alert_title:"세션 만료",session_alert_account_label:"계정",session_alert_apple_account:"Apple 계정",session_alert_sign_out_button:"로그아웃",session_alert_sign_in_again_button:"다시 로그인"},fr={confirm:"Confirm",cancel:"Cancel",close:"Close",signature_requesting:" is requesting a Signature",signature_warning:"After you sign, changes or cancellations are not possible.",signature_sign_button:"Sign",sign_message_title:"Sign Message",sign_typed_data_title:"Sign Data",sign_transaction_title:"Sign Transaction",send_transaction_title:"Send Transaction",send_tx_permission_text:" wants your permission to approve the following transaction.",send_tx_approve_button:"Approve",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",tx_progress_waiting_title:"Waiting for confirmation",tx_progress_waiting_text:"Waiting for transaction receipt...",tx_complete_done_button:"All Done",label_to:"To",label_from:"From",label_network:"Network",label_value:"Value",label_estimated_fee:"Estimated fee",label_est_tx_fee:"Est. Tx Fee",label_max_priority_fee:"Max Priority Fee",label_max_gas_fee:"Max Gas Fee",label_gas_price:"Gas Price",label_gas_limit:"Gas Limit",label_transfer:"Transfer",label_tx_fee:"Tx Fee",label_tx_hash:"Tx Hash",label_total:"Total",label_including_fees:"(including fees)",label_primary_type:"Primary Type",login_selector_title:"CROSS Wallet",login_selector_subtitle:"Sign in instantly with your social account",login_selector_google:"Sign in with Google",login_selector_apple:"Sign in with Apple",login_selector_or:"or",login_selector_terms_template:"By continuing, you agree to NEXUS {tos} and consent to its {pp}",login_selector_terms_tos:"Terms of Service",login_selector_terms_pp:"Privacy Policy.",login_selector_connect_other_wallets:"Connect with Other Wallets",login_selector_connect_other_wallets_desc:"Connect your existing Web3 wallet to manage your assets.",migration_found_title:"Existing Wallet Found",migration_found_description:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recover_button:"Recover",migration_skip_button:"Skip",recovery_pin_input_title:"Enter PIN",recovery_pin_input_placeholder:"Enter your 4-digit PIN",recovery_pin_input_error:"Incorrect PIN. Please try again.",wallet_selector_title:"Select Wallet",wallet_selector_description:"Please select the wallet you previously used for this game to continue.",wallet_selector_info_title:"Why do I need to select a wallet?",wallet_selector_info_desc:"Identifying your previously linked wallet ensures your data and assets are synced correctly.",wallet_selector_add_button:"Add Wallet",wallet_selector_selected:"Selected",wallet_selector_add_error_limit_exceeded:"Account limit reached. Maximum {limit} accounts allowed.",wallet_selector_add_error_generic:"Failed to add a new account. Please try again.",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:"Next",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:"Enter your PIN again to confirm.",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
5
 
5
- For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},ln={ko:cn,en:us};function be(r="en",e){return ln[r]??us}const hs="crossx_access_token",ps="crossx_refresh_token",fs="crossx_user_info",vt=class vt{constructor(e,s,t,n,i,o,a,c){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this._refreshPromise=null,this._migrated=!1;const l=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${l}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${l}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${l}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const s=this.crypto.decodeJWT(e);return s!=null&&s.exp?s.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredRNBridgeSession(){if(!await this.hasValidStoredAccessToken())return!1;try{return!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN)}catch{return!1}}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new _(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new _(h.OAUTH_POPUP_BLOCKED,i):new _(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let s;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const p=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=p.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new _(h.AUTH_FAILED,"Access token 검증 실패");const p=u.payload;s={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",s.id,"email:",s.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,s)}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 d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,!1)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:x}=await this.exchangeFirebaseToken(e,u);let f,g,b;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),g=(i=A.firebase)==null?void 0:i.sign_in_provider;const R=((o=A.firebase)==null?void 0:o.identities)??{};b=A.email??((a=R.email)==null?void 0:a[0]),g==="google.com"?f=(c=R["google.com"])==null?void 0:c[0]:g==="apple.com"&&(f=(l=R["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",g,"hasProviderSub:",!!f,"email:",b??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const A=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const R=await this.crypto.verifyJWT(p);if(n=R.signatureVerified??!1,!R.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const L=R.payload,P=L.email??b??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",L.email??"(없음)","/ Firebase JWT:",b??"(없음)","/ OAuth 콜백:",s??"(없음)","→",P??"(없음)"),t={id:L.sub,email:P,signInProvider:g,providerSub:f},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??s,signInProvider:g,providerSub:f},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const v=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,v),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,s){const t=`${s}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new _(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new _(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;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 s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof _&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(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:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=vt.REFRESH_RELOGIN_CODES.has(c.code);throw new _(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new _(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof _&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof _&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(fs);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(hs);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(ps);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(fs),await this.storage.remove(hs),await this.storage.remove(ps),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof _&&i.code===h.MIGRATION_BACKUP_EXISTS)d.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))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};vt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let It=vt;class dn{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class un{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new _(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Tt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.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 s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class hn{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new _(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class pn{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}function fn(){var e;if(typeof globalThis<"u"&&((e=globalThis.crypto)!=null&&e.getRandomValues)){const s=new Uint8Array(16);return globalThis.crypto.getRandomValues(s),Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("")}return require("crypto").randomBytes(16).toString("hex")}class Se{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const s=Date.now();for(;Date.now()-s<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 Se.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=Se.getBridge(),!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new _(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const s=await this.handshake();return this.context=s,d.log("[RNBridge] Bootstrap initialization complete",{activated:s.isActivated,ttl:`${s.absoluteTtlMs/1e3/60}min`}),s}async handshake(){if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=fn(),s=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:s,hmac:""};try{const n=await this.bridge.handshake(t);if(!n.activated)throw new _(h.AUTH_FAILED,"Bridge handshake rejected by native");return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),walletAddress:n.walletAddress}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new _(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){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");try{const s=await this.bridge.requestFirebaseIdToken(),t=(s.expiresAt-Date.now())/1e3;if(t<60)throw new _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return s}catch(s){throw s instanceof _?s:(d.error("[RNBridge] Firebase token request failed",s),new _(h.AUTH_FAILED,"Firebase token request failed",s))}}async requestFreshFirebaseIdToken(){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");try{const s=await this.bridge.requestFreshFirebaseIdToken();if((s.expiresAt-Date.now())/1e3<60)throw new _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short");return s}catch(s){throw s instanceof _?s:(d.error("[RNBridge] Fresh Firebase token request failed",s),new _(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",s))}}getContext(){return this.context}isActive(){var t;return!(!((t=this.context)!=null&&t.isActivated)||Date.now()-this.context.activatedAt>this.context.absoluteTtlMs)}}var it={environment:"production"};const Fe={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function gn(r){const e=r.environment;return e&&e in Fe?Fe[e]:null}function gs(){try{if(typeof it<"u"){const r=typeof it=="string"?JSON.parse(it):it,e=gn(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Fe)return Fe[r]}catch{}return Fe.production}const _n=2e3,_s=6e4,xn=1e3,mn=1e4,wn="0x77359400",xs="0x3B9ACA00",ms=130,ws=6,ys=18,bs=3e4,yn=5*60*1e3,bn=30*1e3,Rt=100,Sn="crossx-sdk-js/2.2.0";function Ss(r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===48;)e--;return r.slice(0,e)}function vn(r){if(!r||r==="0x0"||r==="0x")return"0";try{const e=BigInt(r);if(e===0n)return"0";const s=10n**BigInt(ys),t=e/s,i=(e%s).toString().padStart(ys,"0"),o=Ss(i).slice(0,ws);return o?`${t}.${o}`:`${t}`}catch{return"?"}}function ot(r,e,s){if(!(!r||r==="0x"||r==="0x0"))try{const t=BigInt(r);if(t===0n)return;const n=10n**BigInt(s),i=t/n,a=(t%n).toString().padStart(s,"0"),c=Ss(a.slice(0,ws));return`${c?`${i}.${c}`:`${i}`} ${e}`}catch{return}}function En(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==ms)throw new _(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${ms} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function An(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function In(r,e){const s=Tn(e);if(r==="0"){if(s!==void 0&&s!==0)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${s}`);return}const t=r.match(/^eip155:(\d+)$/);if(t){const n=Number(t[1]);if(s===void 0)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${r})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(s!==n)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${s})가 chainId (${r}, 예상값: ${n})와 일치하지 않습니다`)}}function Tn(r){if(r==null||typeof r!="object")return;const e=r.domain;if(e==null||typeof e!="object")return;const s=e.chainId;if(s==null)return;const t=Number(s);return Number.isFinite(t)?t:void 0}class Ue{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),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const s=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof _){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Ue.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof _&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=be(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:u?this.deps.maskEmail(u,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const s=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof _){if(t=Ue.parsePinError(n,s),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof _&&(t=Ue.parsePinError(n,s),t))continue;throw n}}}static parsePinError(e,s){if(e.code===h.PIN_WRONG)return{errorMessage:s.pinInput_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:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_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,s){const t=Ue.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Rn{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 kn(r){return r==="google"||r==="apple"}class On{constructor(e){this.deps=e}async signInAgain(){var s,t;this.deps.ensureInitialized();const e=this.deps.getSessionSnapshot();this.deps.setRecoveringSession(!0);try{this.deps.setAuthenticated(!1),this.deps.clearTokenStore();const n=kn(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=((s=i.user)==null?void 0:s.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.sessionAlert_title,message:l.alert_differentAccount,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.sessionAlert_appleAccount):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(s){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.sessionAlert_appleAccount):void 0;if(s instanceof _&&s.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(s instanceof _&&s.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(!(s instanceof _)||s.code!==h.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,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 Cn{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,s){const t=this.deps.getUserId();if(!t)return;const n=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const i=await this.deps.walletProvider.getAddresses(t);if(i.length>0){const a=s?i.find(u=>u.address.toLowerCase()===s.toLowerCase()):void 0,c=e!==void 0?i.find(u=>u.index===e):void 0,l=a??c??i[0];d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",l.address),this.deps.setActiveWallet(l.address,l.index);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(t,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class Nn{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!p){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(p.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const x=p.pinStatus;if(o=x.maxAttempts,i=o-x.remainingAttempts,x.remainingAttempts===0&&x.lockExpiresAt){const f=x.lockExpiresAt*1e3,g=Math.max(1,Math.round((f-Date.now())/1e3)),b=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${g}초, 메시지: ${b}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(g,b),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof _))throw p;if(p.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const x=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:x.sessionAlert_title,message:x.alert_sessionExpired,email:f?this.deps.maskEmail(f,x.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const x=p.details;if(o=(x==null?void 0:x.maxAttempts)??5,(x==null?void 0:x.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const f=((x==null?void 0:x.lockExpiresAt)??0)*1e3,g=Math.max(1,Math.round((f-Date.now())/1e3)),b=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${g}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(g,b),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof _&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof _&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=be(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:x?this.deps.maskEmail(x,p.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const b=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",b.address),b}catch(b){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",b),b}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Pn{constructor(e){this.deps=e}async withResolvedGasAndFee(e,s){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,x]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],s):null,i?this.deps.estimateGas(e,s):null,o?this.deps.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const f=x;if(f){const g=xs;c.maxFeePerGas=`0x${(BigInt(f)+BigInt(g)).toString(16)}`,c.maxPriorityFeePerGas=g,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=wn,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=xs,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Ln{constructor(e){this.crypto=e}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Dn(r){return r?r.includes("google")?"google":r.includes("apple")?"apple":r:null}class Mn{constructor(e){this.deps=e}setActiveWallet(e,s){this.deps.setState({address:e,activeWalletIndex:s}),this.deps.emitAddressChanged({address:e,index:s}),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:s,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const s={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Dn((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(s),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Bn{constructor(e){this.deps=e}async resolveAddress(e){const s=this.deps.getActiveWalletIndex(),t=this.deps.getActiveAddress();if(e===void 0||e===s){if(!t)throw new _(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:t,index:s}}return{address:(await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getAddress(this.deps.getUserId(),e))).address,index:e}}}class $n{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 Wn{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const s=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",s),s==="migration_required"){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return s==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const s=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(s.address,0),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof _&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}}function vs(r,e){const s=r.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${s}/cross-auth${t}`}class Fn{constructor(e){this.deps=e}async registerTokenHistory(e,s,t){if(!(e!=null&&e.trim()))throw new _(h.TX_INVALID_PARAMS,"invalid param chain_id");if(!(s!=null&&s.trim()))throw new _(h.TX_INVALID_PARAMS,"invalid param tx_hash");const n=s.startsWith("0x")?s:`0x${s}`;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=vs(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof _?c:new _(h.UNKNOWN_ERROR,`Failed to register token history: ${c instanceof Error?c.message:String(c)}`)}}async getTokenHistory(e){var n;const s=this.deps.getApiBaseUrl(),t=new URL(vs(s,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new _(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof _?i:new _(h.UNKNOWN_ERROR,`Failed to fetch token history: ${i instanceof Error?i.message:String(i)}`)}}async registerHistoryFireAndForget(e,s,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,s,t);return}catch(c){if(c instanceof _&&c.message.includes("404")&&a<i-1){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,s){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${s==="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 kt(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const $e=class $e extends pn{constructor(e,s,t,n,i,o,a,c,l,u,p){var x,f;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&ds(e.logger),this.confirmation=l,this.pinStore=p??new Tt,this.stateManager=new Mn({setState:g=>{g.authenticated!==void 0&&(this.authenticated=g.authenticated),g.userId!==void 0&&(this.userId=g.userId),g.address!==void 0&&(this.address=g.address),g.activeWalletIndex!==void 0&&(this.activeWalletIndex=g.activeWalletIndex),g.userEmail!==void 0&&(this.userEmail=g.userEmail),g.providerSub!==void 0&&(this.providerSub=g.providerSub),g.loginType!==void 0&&(this.loginType=g.loginType),g.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=g.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:g,index:b})=>{this.emit("addressChanged",{address:g,index:b})},emitAuthChanged:({isAuthenticated:g,address:b,userId:v})=>{this.emit("authChanged",{isAuthenticated:g,address:b,userId:v})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:$e.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ue({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:kt,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Rn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Cn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(g,b)=>this.setActiveWallet(g,b)}),this.migrationOrchestrator=new Nn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(g,b)=>this.migrateWalletUseCase.execute(g,b),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:kt,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var g;return((g=this._config.migration)==null?void 0:g.allowSkip)??!0}}),this.transactionLifecycleService=new Pn({getActiveAddress:()=>this.address,estimateGas:(g,b)=>this.estimateGas(g,b),getBaseFeePerGas:g=>this.getBaseFeePerGas(g),jsonRpcCall:(g,b,v)=>this.jsonRpc.call(g,b,v)}),this.signatureVerifier=new Ln(this.crypto),this.addressResolverService=new Bn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new $n({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Wn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(g,b)=>this.setActiveWallet(g,b)}),this.tokenHistoryService=new Fn({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new On({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:g=>{this._isRecoveringSession=g},setAuthenticated:g=>{this.authenticated=g},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:g=>this.signInUseCase.execute(g),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:g=>this.confirmation.showSessionAlert(g),clearAuthState:()=>this.clearAuthState(),applyAuthResult:g=>this.applyAuthResult(g),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:kt}),this.chainRegistry=u,this.jsonRpc=new hn(u,i),this.signInUseCase=new It(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new dn(this.internalConfig,t,c),this.migrateWalletUseCase=new un(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(f=a.setTokenRefresher)==null||f.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var s,t;d.log("[CROSSx SDK] v2.2.0 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=gs();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get($e.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(!(e!=null&&e.preferredWalletAddress)&&this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(o,a)}catch(u){if(!(u instanceof _&&u.code===h.PIN_CANCELLED))throw u;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,d.info("[CROSSx SDK] v2.2.0 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new _(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!Se.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new Se({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.2.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),s=await e.initialize();return this._rnBridgeService=e,this._rnBridgeWalletAddress=s.walletAddress,this.subscribeBridgeWalletChanged(),d.log("[CROSSx] RN Bridge Handshake 성공",{walletAddress:s.walletAddress??"(없음)"}),await this.signInUseCase.hasValidStoredAccessToken()?(await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 — native sign delegation 활성")),null):(d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null)}catch(e){return d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const s=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(s);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(s){const t=s instanceof Error?s.message:String(s);return t.includes("USER_REJECTED")||t.includes("rejected")?(d.log("[CROSSx] Bridge 로그인 거부 — bridge 비활성화, OAuth fallback"),this._rnBridgeService=null):d.warn("[CROSSx] Bridge 로그인 실패",s),null}}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new _(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFreshFirebaseIdToken()}catch(e){throw d.error("[CROSSx] Fresh Firebase token request failed:",e),new _(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return Se.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t!=null&&t.success)return t}let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:rn(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new _(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");s={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof _?t:new _(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:s,...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,s);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,s);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof _&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof _?s:new _(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof _?t:new _(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=Se.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(s){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",s)}this._rnBridgeService=null,this._rnBridgeWalletAddress=void 0}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}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof _&&s.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}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 s=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(s.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof _?s:new _(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}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){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=s.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,s){if(e.length<2)return null;if(s){const t=e.find(n=>n.address.toLowerCase()===s.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof _?s:new _(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(be(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:s,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:s,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof _?i:new _(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");In(e,s);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:s,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:s,from:n.address},execute:o=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address)});return En(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,s){return this.signTypedData($e.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=At(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 An(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,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.transactionLifecycleService.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=At(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return p.txHash??p.signature}}),a=(s.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,Sn).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{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,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??xn,i=mn,o=t.timeoutMs??_s,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new _(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,v;if(this._isAuthenticatedViaRNBridge){const A=Se.getBridge();if(A!=null&&A.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(A,e,s,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??_n,l=i??((v=this._config.receiptPolling)==null?void 0:v.timeoutMs)??_s,u=At(e),p=s.from??"";let x,f;const g=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{x=A;const R=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),L=s.value?BigInt(s.value):0n,P=ot(s.value,u.symbol,u.decimals),G=ot("0x"+R.toString(16),u.symbol,u.decimals),q=ot("0x"+(L+R).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:A.from,to:A.to??s.to,amount:P,fees:G,total:q,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(f=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:p,to:s.to,amount:ot(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:s.to},g),f)throw f;return{chainId:e,txHash:a,receipt:x}}async bridgeSendTransactionWithWaitForReceipt(e,s,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:s,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:s,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()}async changePin(e,s){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,s),this.pinStore.set(s),d.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(s){const t=s instanceof Error?s.message:String(s);throw new _(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){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],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new _(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new _(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"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 s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:vn(n),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 s=this._providers.get(e);return s||(s=new ls(this,e),this._providers.set(e,s)),s}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(s=>{try{s.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,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,s){const t=this.address;this.stateManager.setActiveWallet(e,s),t&&e&&t.toLowerCase()!==e.toLowerCase()&&this.emitAccountsChanged(e)}subscribeBridgeWalletChanged(){const e=Se.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",s=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!s||typeof s!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",s);return}const t=s,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source}),this.setActiveWallet(n,0),this._rnBridgeWalletAddress=n)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,s){return this.walletLifecycleService.loadWalletAfterAuth(e,s)}async resolveAddress(e){return this.addressResolverService.resolveAddress(e)}ensureInitialized(){this.authGuardService.ensureInitialized()}ensureAuthenticated(){this.authGuardService.ensureAuthenticated()}async registerTokenHistory(e,s,t){return this.withSessionRecovery(()=>this.tokenHistoryService.registerTokenHistory(e,s,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(),ds(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};$e.WALLET_PREF_KEY="wallet_preference",$e.OFFCHAIN_CHAIN_ID="0";let at=$e;class Un{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return d.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw d.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Ot="crossx-sdk",Hn=1,ge="data",Pe="keys",ct="aes-primary",Gn=12;class Es{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,Hn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ge)||i.createObjectStore(ge),i.objectStoreNames.contains(Pe)||i.createObjectStore(Pe)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Pe,ct);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Pe,ct,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Ot)return null;try{const e=await this.openDB(Ot),s=e.transaction([Pe,ge],"readonly"),t=s.objectStore(Pe).get(ct),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=s.objectStore(ge).getAll(),o=s.objectStore(ge).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Pe,ct,n);for(let l=0;l<c.length;l++)await this.idbPut(ge,String(c[l]),a[l]);return indexedDB.deleteDatabase(Ot),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(Gn);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(ge,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(ge,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return d.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ge,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ge)}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 Ct=crypto,As=r=>r instanceof CryptoKey,lt=new TextEncoder,Ze=new TextDecoder;function Kn(...r){const e=r.reduce((n,{length:i})=>n+i,0),s=new Uint8Array(e);let t=0;for(const n of r)s.set(n,t),t+=n.length;return s}const qn=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},Re=r=>{let e=r;e instanceof Uint8Array&&(e=Ze.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return qn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Q extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Q.code="ERR_JOSE_GENERIC";class de extends Q{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}de.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Nt extends Q{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}Nt.code="ERR_JWT_EXPIRED";class Is extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Is.code="ERR_JOSE_ALG_NOT_ALLOWED";class _e extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}_e.code="ERR_JOSE_NOT_SUPPORTED";class Vn extends Q{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}Vn.code="ERR_JWE_DECRYPTION_FAILED";class zn extends Q{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}zn.code="ERR_JWE_INVALID";class Z extends Q{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Z.code="ERR_JWS_INVALID";class xe extends Q{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class Jn extends Q{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Jn.code="ERR_JWK_INVALID";class Pt extends Q{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Pt.code="ERR_JWKS_INVALID";class Lt extends Q{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Lt.code="ERR_JWKS_NO_MATCHING_KEY";class Ts extends Q{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}Ts.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Rs extends Q{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}Rs.code="ERR_JWKS_TIMEOUT";class ks extends Q{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}ks.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function me(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Qe(r,e){return r.name===e}function Dt(r){return parseInt(r.name.slice(4),10)}function Yn(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function jn(r,e){if(e.length&&!e.some(s=>r.usages.includes(s))){let s="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();s+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?s+=`one of ${e[0]} or ${e[1]}.`:s+=`${e[0]}.`;throw new TypeError(s)}}function Xn(r,e,...s){switch(e){case"HS256":case"HS384":case"HS512":{if(!Qe(r.algorithm,"HMAC"))throw me("HMAC");const t=parseInt(e.slice(2),10);if(Dt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Qe(r.algorithm,"RSASSA-PKCS1-v1_5"))throw me("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Dt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Qe(r.algorithm,"RSA-PSS"))throw me("RSA-PSS");const t=parseInt(e.slice(2),10);if(Dt(r.algorithm.hash)!==t)throw me(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw me("Ed25519 or Ed448");break}case"Ed25519":{if(!Qe(r.algorithm,"Ed25519"))throw me("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Qe(r.algorithm,"ECDSA"))throw me("ECDSA");const t=Yn(e);if(r.algorithm.namedCurve!==t)throw me(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}jn(r,s)}function Os(r,e,...s){var t;if(s=s.filter(Boolean),s.length>2){const n=s.pop();r+=`one of type ${s.join(", ")}, or ${n}.`}else s.length===2?r+=`one of type ${s[0]} or ${s[1]}.`:r+=`of type ${s[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const Cs=(r,...e)=>Os("Key must be ",r,...e);function Ns(r,e,...s){return Os(`Key for the ${r} algorithm must be `,e,...s)}const Ps=r=>As(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",dt=["CryptoKey"],Zn=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let s;for(const t of e){const n=Object.keys(t);if(!s||s.size===0){s=new Set(n);continue}for(const i of n){if(s.has(i))return!1;s.add(i)}}return!0};function Qn(r){return typeof r=="object"&&r!==null}function ve(r){if(!Qn(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const ei=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:s}=e.algorithm;if(typeof s!="number"||s<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function He(r){return ve(r)&&typeof r.kty=="string"}function ti(r){return r.kty!=="oct"&&typeof r.d=="string"}function si(r){return r.kty!=="oct"&&typeof r.d>"u"}function ri(r){return He(r)&&r.kty==="oct"&&typeof r.k=="string"}function ni(r){let e,s;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},s=r.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(r.alg.slice(-3),10)||1}`},s=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},s=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},s=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},s=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new _e('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:s}}const Ls=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:s}=ni(r),t=[e,r.ext??!1,r.key_ops??s],n={...r};return delete n.alg,delete n.use,Ct.subtle.importKey("jwk",n,...t)},Ds=r=>Re(r);let Ge,Ke;const Ms=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ut=async(r,e,s,t,n=!1)=>{let i=r.get(e);if(i!=null&&i[t])return i[t];const o=await Ls({...s,alg:t});return n&&Object.freeze(e),i?i[t]=o:r.set(e,{[t]:o}),o},ii={normalizePublicKey:(r,e)=>{if(Ms(r)){let s=r.export({format:"jwk"});return delete s.d,delete s.dp,delete s.dq,delete s.p,delete s.q,delete s.qi,s.k?Ds(s.k):(Ke||(Ke=new WeakMap),ut(Ke,r,s,e))}return He(r)?r.k?Re(r.k):(Ke||(Ke=new WeakMap),ut(Ke,r,r,e,!0)):r},normalizePrivateKey:(r,e)=>{if(Ms(r)){let s=r.export({format:"jwk"});return s.k?Ds(s.k):(Ge||(Ge=new WeakMap),ut(Ge,r,s,e))}return He(r)?r.k?Re(r.k):(Ge||(Ge=new WeakMap),ut(Ge,r,r,e,!0)):r}};async function Bs(r,e){if(!ve(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new _e('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Ls({...r,alg:e});default:throw new _e('Unsupported "kty" (Key Type) Parameter value')}}const qe=r=>r==null?void 0:r[Symbol.toStringTag],Mt=(r,e,s)=>{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,s))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},oi=(r,e,s,t)=>{if(!(e instanceof Uint8Array)){if(t&&He(e)){if(ri(e)&&Mt(r,e,s))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(Ns(r,e,...dt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${qe(e)} instances for symmetric algorithms must be of type "secret"`)}},ai=(r,e,s,t)=>{if(t&&He(e))switch(s){case"sign":if(ti(e)&&Mt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(si(e)&&Mt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ps(e))throw new TypeError(Ns(r,e,...dt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${qe(e)} instances for asymmetric algorithms must not be of type "secret"`);if(s==="sign"&&e.type==="public")throw new TypeError(`${qe(e)} instances for asymmetric algorithm signing must be of type "private"`);if(s==="decrypt"&&e.type==="public")throw new TypeError(`${qe(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&s==="verify"&&e.type==="private")throw new TypeError(`${qe(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&s==="encrypt"&&e.type==="private")throw new TypeError(`${qe(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function $s(r,e,s,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?oi(e,s,t,r):ai(e,s,t,r)}$s.bind(void 0,!1);const Ws=$s.bind(void 0,!0);function ci(r,e,s,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new r('"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 r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;s!==void 0?i=new Map([...Object.entries(s),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new _e(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new r(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new r(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const li=(r,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(s=>typeof s!="string")))throw new TypeError(`"${r}" option must be an array of strings`);if(e)return new Set(e)};function di(r,e){const s=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new _e(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function ui(r,e,s){if(e=await ii.normalizePublicKey(e,r),As(e))return Xn(e,r,s),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(Cs(e,...dt));return Ct.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(Cs(e,...dt,"Uint8Array","JSON Web Key"))}const hi=async(r,e,s,t)=>{const n=await ui(r,e,"verify");ei(r,n);const i=di(r,n.algorithm);try{return await Ct.subtle.verify(i,n,s,t)}catch{return!1}};async function pi(r,e,s){if(!ve(r))throw new Z("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new Z("JWS Protected Header incorrect type");if(r.payload===void 0)throw new Z("JWS Payload missing");if(typeof r.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(r.header!==void 0&&!ve(r.header))throw new Z("JWS Unprotected Header incorrect type");let t={};if(r.protected)try{const b=Re(r.protected);t=JSON.parse(Ze.decode(b))}catch{throw new Z("JWS Protected Header is invalid")}if(!Zn(t,r.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...r.header},i=ci(Z,new Map([["b64",!0]]),s==null?void 0:s.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&li("algorithms",s.algorithms);if(c&&!c.has(a))throw new Is('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof r.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,r),l=!0,Ws(a,e,"verify"),He(e)&&(e=await Bs(e,a))):Ws(a,e,"verify");const u=Kn(lt.encode(r.protected??""),lt.encode("."),typeof r.payload=="string"?lt.encode(r.payload):r.payload);let p;try{p=Re(r.signature)}catch{throw new Z("Failed to base64url decode the signature")}if(!await hi(a,e,p,u))throw new ks;let f;if(o)try{f=Re(r.payload)}catch{throw new Z("Failed to base64url decode the payload")}else typeof r.payload=="string"?f=lt.encode(r.payload):f=r.payload;const g={payload:f};return r.protected!==void 0&&(g.protectedHeader=t),r.header!==void 0&&(g.unprotectedHeader=r.header),l?{...g,key:e}:g}async function fi(r,e,s){if(r instanceof Uint8Array&&(r=Ze.decode(r)),typeof r!="string")throw new Z("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=r.split(".");if(o!==3)throw new Z("Invalid Compact JWS");const a=await pi({payload:n,protected:t,signature:i},e,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const gi=r=>Math.floor(r.getTime()/1e3),Fs=60,Us=Fs*60,Bt=Us*24,_i=Bt*7,xi=Bt*365.25,mi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Hs=r=>{const e=mi.exec(r);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const s=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(s*Fs);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(s*Us);break;case"day":case"days":case"d":n=Math.round(s*Bt);break;case"week":case"weeks":case"w":n=Math.round(s*_i);break;default:n=Math.round(s*xi);break}return e[1]==="-"||e[4]==="ago"?-n:n},Gs=r=>r.toLowerCase().replace(/^application\//,""),wi=(r,e)=>typeof r=="string"?e.includes(r):Array.isArray(r)?e.some(Set.prototype.has.bind(new Set(r))):!1,yi=(r,e,s={})=>{let t;try{t=JSON.parse(Ze.decode(e))}catch{}if(!ve(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=s;if(n&&(typeof r.typ!="string"||Gs(r.typ)!==Gs(n)))throw new de('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=s,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const g of new Set(u.reverse()))if(!(g in t))throw new de(`missing required "${g}" claim`,t,g,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new de('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new de('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!wi(t.aud,typeof c=="string"?[c]:c))throw new de('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof s.clockTolerance){case"string":p=Hs(s.clockTolerance);break;case"number":p=s.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:x}=s,f=gi(x||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new de('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new de('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>f+p)throw new de('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new de('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=f-p)throw new Nt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const g=f-t.iat,b=typeof l=="number"?l:Hs(l);if(g-p>b)throw new Nt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(g<0-p)throw new de('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function bi(r,e,s){var o;const t=await fi(r,e,s);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:yi(t.protectedHeader,t.payload,s),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Si(r){switch(typeof r=="string"&&r.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new _e('Unsupported "alg" value for a JSON Web Key Set')}}function vi(r){return r&&typeof r=="object"&&Array.isArray(r.keys)&&r.keys.every(Ei)}function Ei(r){return ve(r)}function Ks(r){return typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}class Ai{constructor(e){if(this._cached=new WeakMap,!vi(e))throw new Pt("JSON Web Key Set malformed");this._jwks=Ks(e)}async getKey(e,s){const{alg:t,kid:n}={...e,...s==null?void 0:s.header},i=Si(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Lt;if(c!==1){const l=new Ts,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await qs(u,p,t)}catch{}},l}return qs(this._cached,a,t)}}async function qs(r,e,s){const t=r.get(e)||r.set(e,{}).get(e);if(t[s]===void 0){const n=await Bs({...e,ext:!0},s);if(n instanceof Uint8Array||n.type!=="public")throw new Pt("JSON Web Key Set members must be public keys");t[s]=n}return t[s]}function Vs(r){const e=new Ai(r),s=async(t,n)=>e.getKey(t,n);return Object.defineProperties(s,{jwks:{value:()=>Ks(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),s}const Ii=async(r,e,s)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(r.href,{signal:t?t.signal:void 0,redirect:"manual",headers:s.headers}).catch(a=>{throw i?new Rs:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new Q("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Q("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Ti(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let $t;(typeof navigator>"u"||!((Qr=(Et=navigator.userAgent)==null?void 0:Et.startsWith)!=null&&Qr.call(Et,"Mozilla/5.0 ")))&&($t="jose/v5.10.0");const Wt=Symbol();function Ri(r,e){return!(typeof r!="object"||r===null||!("uat"in r)||typeof r.uat!="number"||Date.now()-r.uat>=e||!("jwks"in r)||!ve(r.jwks)||!Array.isArray(r.jwks.keys)||!Array.prototype.every.call(r.jwks.keys,ve))}class ki{constructor(e,s){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:s==null?void 0:s.agent,headers:s==null?void 0:s.headers},this._timeoutDuration=typeof(s==null?void 0:s.timeoutDuration)=="number"?s==null?void 0:s.timeoutDuration:5e3,this._cooldownDuration=typeof(s==null?void 0:s.cooldownDuration)=="number"?s==null?void 0:s.cooldownDuration:3e4,this._cacheMaxAge=typeof(s==null?void 0:s.cacheMaxAge)=="number"?s==null?void 0:s.cacheMaxAge:6e5,(s==null?void 0:s[Wt])!==void 0&&(this._cache=s==null?void 0:s[Wt],Ri(s==null?void 0:s[Wt],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,s){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,s)}catch(t){if(t instanceof Lt&&this.coolingDown()===!1)return await this.reload(),this._local(e,s);throw t}}async reload(){this._pendingFetch&&Ti()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);$t&&!e.has("User-Agent")&&(e.set("User-Agent",$t),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Ii(this._url,this._timeoutDuration,this._options).then(s=>{this._local=Vs(s),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=s),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(s=>{throw this._pendingFetch=void 0,s})),await this._pendingFetch}}function Oi(r,e){const s=new ki(r,e),t=async(n,i)=>s.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!s._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=s._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Ci=Re;function Ni(r){if(typeof r!="string")throw new xe("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new xe("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new xe("Invalid JWT");if(!e)throw new xe("JWTs must contain a payload");let t;try{t=Ci(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Ze.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!ve(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ft(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ee(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function V(r,e,s=""){const t=Ft(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function zs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ee(r.outputLen),Ee(r.blockLen)}function Ve(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Js(r,e){V(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Pi(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function ze(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Ut(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function we(r,e){return r<<32-e|r>>>e}const Li=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Di(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Mi(r){for(let e=0;e<r.length;e++)r[e]=Di(r[e]);return r}const Ys=Li?r=>r:Mi,js=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Bi=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function et(r){if(V(r),js)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Bi[r[s]];return e}const Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xs(r){if(r>=Ae._0&&r<=Ae._9)return r-Ae._0;if(r>=Ae.A&&r<=Ae.F)return r-(Ae.A-10);if(r>=Ae.a&&r<=Ae.f)return r-(Ae.a-10)}function ht(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(js)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=Xs(r.charCodeAt(i)),a=Xs(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];V(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Zs(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Qs(r=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(r))}const $i=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Wi(r,e,s){return r&e^~r&s}function Fi(r,e,s){return r&e^r&s^e&s}class Ui{constructor(e,s,t,n){C(this,"blockLen");C(this,"outputLen");C(this,"padOffset");C(this,"isLE");C(this,"buffer");C(this,"view");C(this,"finished",!1);C(this,"length",0);C(this,"pos",0);C(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ut(this.buffer)}update(e){Ve(this),V(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Ut(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ve(this),Js(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,ze(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let p=o;p<n;p++)s[p]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Ut(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,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%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),pt=BigInt(2**32-1),er=BigInt(32);function Hi(r,e=!1){return e?{h:Number(r&pt),l:Number(r>>er&pt)}:{h:Number(r>>er&pt)|0,l:Number(r&pt)|0}}function Gi(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=Hi(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const Ki=(r,e,s)=>r<<s|e>>>32-s,qi=(r,e,s)=>e<<s|r>>>32-s,Vi=(r,e,s)=>e<<s-32|r>>>64-s,zi=(r,e,s)=>r<<s-32|e>>>64-s,Ji=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]),Ce=new Uint32Array(64);class Yi extends Ui{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|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,s){for(let p=0;p<16;p++,s+=4)Ce[p]=e.getUint32(s,!1);for(let p=16;p<64;p++){const x=Ce[p-15],f=Ce[p-2],g=we(x,7)^we(x,18)^x>>>3,b=we(f,17)^we(f,19)^f>>>10;Ce[p]=b+Ce[p-7]+g+Ce[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const x=we(a,6)^we(a,11)^we(a,25),f=u+x+Wi(a,c,l)+Ji[p]+Ce[p]|0,b=(we(t,2)^we(t,13)^we(t,22))+Fi(t,n,i)|0;u=l,l=c,c=a,a=o+f|0,o=i,i=n,n=t,t=f+b|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){ze(Ce)}destroy(){this.set(0,0,0,0,0,0,0,0),ze(this.buffer)}}class ji extends Yi{constructor(){super(32);C(this,"A",Oe[0]|0);C(this,"B",Oe[1]|0);C(this,"C",Oe[2]|0);C(this,"D",Oe[3]|0);C(this,"E",Oe[4]|0);C(this,"F",Oe[5]|0);C(this,"G",Oe[6]|0);C(this,"H",Oe[7]|0)}}const Xi=Zs(()=>new ji,$i(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ht=BigInt(0),Gt=BigInt(1);function ft(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function tr(r){if(typeof r=="bigint"){if(!xt(r))throw new Error("positive bigint expected, got "+r)}else Ee(r);return r}function gt(r){const e=tr(r).toString(16);return e.length&1?"0"+e:e}function sr(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Ht:BigInt("0x"+r)}function _t(r){return sr(et(r))}function rr(r){return sr(et(Zi(V(r)).reverse()))}function Kt(r,e){Ee(e),r=tr(r);const s=ht(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function nr(r,e){return Kt(r,e).reverse()}function Zi(r){return Uint8Array.from(r)}const xt=r=>typeof r=="bigint"&&Ht<=r;function Qi(r,e,s){return xt(r)&&xt(e)&&xt(s)&&e<=r&&r<s}function eo(r,e,s,t){if(!Qi(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function to(r){let e;for(e=0;r>Ht;r>>=Gt,e+=1);return e}const qt=r=>(Gt<<BigInt(r))-Gt;function so(r,e,s){if(Ee(r,"hashLen"),Ee(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=v=>new Uint8Array(v),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},x=(...v)=>s(l,ke(c,...v)),f=(v=n)=>{l=x(i,v),c=x(),v.length!==0&&(l=x(o,v),c=x())},g=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let v=0;const A=[];for(;v<e;){c=x();const R=c.slice();A.push(R),v+=c.length}return ke(...A)};return(v,A)=>{p(),f(v);let R;for(;!(R=A(g()));)f();return p(),R}}function Vt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[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(s,!0)}function ir(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ie=BigInt(0),re=BigInt(1),Le=BigInt(2),or=BigInt(3),ar=BigInt(4),cr=BigInt(5),ro=BigInt(7),lr=BigInt(8),no=BigInt(9),dr=BigInt(16);function ue(r,e){const s=r%e;return s>=ie?s:e+s}function le(r,e,s){let t=r;for(;e-- >ie;)t*=t,t%=s;return t}function ur(r,e){if(r===ie)throw new Error("invert: expected non-zero number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let s=ue(r,e),t=e,n=ie,i=re;for(;s!==ie;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==re)throw new Error("invert: does not exist");return ue(n,e)}function zt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function hr(r,e){const s=(r.ORDER+re)/ar,t=r.pow(e,s);return zt(r,t,e),t}function io(r,e){const s=(r.ORDER-cr)/lr,t=r.mul(e,Le),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,Le),n),a=r.mul(i,r.sub(o,r.ONE));return zt(r,a,e),a}function oo(r){const e=mt(r),s=pr(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+ro)/dr;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),x=a.mul(l,i),f=a.eql(a.sqr(u),c),g=a.eql(a.sqr(p),c);l=a.cmov(l,u,f),u=a.cmov(x,p,g);const b=a.eql(a.sqr(u),c),v=a.cmov(l,u,b);return zt(a,v,c),v}}function pr(r){if(r<or)throw new Error("sqrt is not defined for small field");let e=r-re,s=0;for(;e%Le===ie;)e/=Le,s++;let t=Le;const n=mt(r);for(;gr(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return hr;let i=n.pow(t,e);const o=(e+re)/Le;return function(c,l){if(c.is0(l))return l;if(gr(c,l)!==1)throw new Error("Cannot find square root");let u=s,p=c.mul(c.ONE,i),x=c.pow(l,e),f=c.pow(l,o);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let g=1,b=c.sqr(x);for(;!c.eql(b,c.ONE);)if(g++,b=c.sqr(b),g===u)throw new Error("Cannot find square root");const v=re<<BigInt(u-g-1),A=c.pow(p,v);u=g,p=c.sqr(A),x=c.mul(x,p),f=c.mul(f,A)}return f}}function ao(r){return r%ar===or?hr:r%lr===cr?io:r%dr===no?oo(r):pr(r)}const co=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function lo(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=co.reduce((t,n)=>(t[n]="function",t),e);return Vt(r,s),r}function uo(r,e,s){if(s<ie)throw new Error("invalid exponent, negatives unsupported");if(s===ie)return r.ONE;if(s===re)return e;let t=r.ONE,n=e;for(;s>ie;)s&re&&(t=r.mul(t,n)),n=r.sqr(n),s>>=re;return t}function fr(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function gr(r,e){const s=(r.ORDER-re)/Le,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function ho(r,e){e!==void 0&&Ee(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class po{constructor(e,s={}){C(this,"ORDER");C(this,"BITS");C(this,"BYTES");C(this,"isLE");C(this,"ZERO",ie);C(this,"ONE",re);C(this,"_lengths");C(this,"_sqrt");C(this,"_mod");var o;if(e<=ie)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=ho(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 ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ie<=e&&e<this.ORDER}is0(e){return e===ie}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&re)===re}neg(e){return ue(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ue(e*e,this.ORDER)}add(e,s){return ue(e+s,this.ORDER)}sub(e,s){return ue(e-s,this.ORDER)}mul(e,s){return ue(e*s,this.ORDER)}pow(e,s){return uo(this,e,s)}div(e,s){return ue(e*ur(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return ur(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=ao(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?nr(e,this.BYTES):Kt(e,this.BYTES)}fromBytes(e,s=!1){V(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?rr(e):_t(e);if(a&&(c=ue(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return fr(this,e)}cmov(e,s,t){return t?s:e}}function mt(r,e={}){return new po(r,e)}function _r(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function xr(r){const e=_r(r);return e+Math.ceil(e/2)}function fo(r,e,s=!1){V(r);const t=r.length,n=_r(e),i=xr(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?rr(r):_t(r),a=ue(o,e-re)+re;return s?nr(a,n):Kt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Je=BigInt(0),De=BigInt(1);function wt(r,e){const s=e.negate();return r?s:e}function mr(r,e){const s=fr(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function wr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Jt(r,e){wr(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=qt(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function yr(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,p=a===0,x=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:x,isNegF:f,offsetF:l}}const Yt=new WeakMap,br=new WeakMap;function jt(r){return br.get(r)||1}function Sr(r){if(r!==Je)throw new Error("invalid wNAF")}class go{constructor(e,s){C(this,"BASE");C(this,"ZERO");C(this,"Fn");C(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Je;)s&De&&(t=t.add(n)),n=n.double(),s>>=De;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Jt(s,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,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Jt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:x,offsetF:f}=yr(t,a,o);t=c,u?i=i.add(wt(x,s[f])):n=n.add(wt(p,s[l]))}return Sr(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=Jt(e,this.bits);for(let o=0;o<i.windows&&t!==Je;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=yr(t,o,i);if(t=a,!l){const p=s[c];n=n.add(u?p.negate():p)}}return Sr(t),n}getPrecomputes(e,s,t){let n=Yt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Yt.set(s,n))),n}cached(e,s,t){const n=jt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=jt(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){wr(s,this.bits),br.set(e,s),Yt.delete(e)}hasCache(e){return jt(e)!==1}}function _o(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>Je||t>Je;)s&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),s>>=De,t>>=De;return{p1:i,p2:o}}function vr(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return lo(e),e}else return mt(r,{isLE:s})}function xo(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Je))throw new Error(`CURVE.${c} must be positive bigint`)}const n=vr(e.p,s.Fp,t),i=vr(e.n,s.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 mo(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Er{constructor(e,s){C(this,"oHash");C(this,"iHash");C(this,"blockLen");C(this,"outputLen");C(this,"finished",!1);C(this,"destroyed",!1);if(zs(e),V(s,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(s.length>t?e.create().update(s).digest():s);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),ze(n)}update(e){return Ve(this),this.iHash.update(e),this}digestInto(e){Ve(this),V(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:s,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=s._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 Ar=(r,e,s)=>new Er(r,e).update(s).digest();Ar.create=(r,e)=>new Er(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ir=(r,e)=>(r+(r>=0?e:-e)/Tr)/e;function wo(r,e,s){const[[t,n],[i,o]]=e,a=Ir(o*r,s),c=Ir(-n*r,s);let l=r-a*t-c*i,u=-a*n-c*o;const p=l<Ie,x=u<Ie;p&&(l=-l),x&&(u=-u);const f=qt(Math.ceil(to(s)/2))+Ye;if(l<Ie||l>=f||u<Ie||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:p,k1:l,k2neg:x,k2:u}}function Xt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Zt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ft(s.lowS,"lowS"),ft(s.prehash,"prehash"),s.format!==void 0&&Xt(s.format),s}class yo extends Error{constructor(e=""){super(e)}}const Ne={Err:yo,_tlv:{encode:(r,e)=>{const{Err:s}=Ne;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=gt(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?gt(n.length/2|128):"";return gt(r)+i+n+e},decode(r,e){const{Err:s}=Ne;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("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 s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Ne;if(r<Ie)throw new e("integer: negative integers are not allowed");let s=gt(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Ne;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return _t(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Ne,n=V(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Ne,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Ye=BigInt(1),Tr=BigInt(2),yt=BigInt(3),bo=BigInt(4);function So(r,e={}){const s=xo("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;Vt(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=kr(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p($,m,w){const{x:T,y:O}=m.toAffine(),B=t.toBytes(T);if(ft(w,"isCompressed"),w){u();const y=!t.isOdd(O);return ke(Rr(y),B)}else return ke(Uint8Array.of(4),B,t.toBytes(O))}function x($){V($,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,T=$.length,O=$[0],B=$.subarray(1);if(T===m&&(O===2||O===3)){const y=t.fromBytes(B);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const S=b(y);let E;try{E=t.sqrt(S)}catch(U){const W=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}u();const I=t.isOdd(E);return(O&1)===1!==I&&(E=t.neg(E)),{x:y,y:E}}else if(T===w&&O===4){const y=t.BYTES,S=t.fromBytes(B.subarray(0,y)),E=t.fromBytes(B.subarray(y,y*2));if(!v(S,E))throw new Error("bad point: is not on curve");return{x:S,y:E}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${w}`)}const f=e.toBytes||p,g=e.fromBytes||x;function b($){const m=t.sqr($),w=t.mul(m,$);return t.add(t.add(w,t.mul($,i.a)),i.b)}function v($,m){const w=t.sqr(m),T=b($);return t.eql(w,T)}if(!v(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(i.a,yt),bo),R=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(A,R)))throw new Error("bad curve params: a or b");function L($,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${$}`);return m}function P($){if(!($ instanceof X))throw new Error("Weierstrass Point expected")}function G($){if(!c||!c.basises)throw new Error("no endo");return wo($,c.basises,n.ORDER)}const q=ir(($,m)=>{const{X:w,Y:T,Z:O}=$;if(t.eql(O,t.ONE))return{x:w,y:T};const B=$.is0();m==null&&(m=B?t.ONE:t.inv(O));const y=t.mul(w,m),S=t.mul(T,m),E=t.mul(O,m);if(B)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:y,y:S}}),te=ir($=>{if($.is0()){if(e.allowInfinityPoint&&!t.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=$.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!v(m,w))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function H($,m,w,T,O){return w=new X(t.mul(w.X,$),w.Y,w.Z),m=wt(T,m),w=wt(O,w),m.add(w)}const D=class D{constructor(m,w,T){C(this,"X");C(this,"Y");C(this,"Z");this.X=L("x",m),this.Y=L("y",w,!0),this.Z=L("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:T}=m||{};if(!m||!t.isValid(w)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof D)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(T)?D.ZERO:new D(w,T,t.ONE)}static fromBytes(m){const w=D.fromAffine(g(V(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return D.fromBytes(ht(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return F.createCache(this,m),w||this.multiply(yt),this}assertValidity(){te(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){P(m);const{X:w,Y:T,Z:O}=this,{X:B,Y:y,Z:S}=m,E=t.eql(t.mul(w,S),t.mul(B,O)),I=t.eql(t.mul(T,S),t.mul(y,O));return E&&I}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,T=t.mul(w,yt),{X:O,Y:B,Z:y}=this;let S=t.ZERO,E=t.ZERO,I=t.ZERO,k=t.mul(O,O),U=t.mul(B,B),W=t.mul(y,y),M=t.mul(O,B);return M=t.add(M,M),I=t.mul(O,y),I=t.add(I,I),S=t.mul(m,I),E=t.mul(T,W),E=t.add(S,E),S=t.sub(U,E),E=t.add(U,E),E=t.mul(S,E),S=t.mul(M,S),I=t.mul(T,I),W=t.mul(m,W),M=t.sub(k,W),M=t.mul(m,M),M=t.add(M,I),I=t.add(k,k),k=t.add(I,k),k=t.add(k,W),k=t.mul(k,M),E=t.add(E,k),W=t.mul(B,y),W=t.add(W,W),k=t.mul(W,M),S=t.sub(S,k),I=t.mul(W,U),I=t.add(I,I),I=t.add(I,I),new D(S,E,I)}add(m){P(m);const{X:w,Y:T,Z:O}=this,{X:B,Y:y,Z:S}=m;let E=t.ZERO,I=t.ZERO,k=t.ZERO;const U=i.a,W=t.mul(i.b,yt);let M=t.mul(w,B),K=t.mul(T,y),j=t.mul(O,S),ce=t.add(w,T),Y=t.add(B,y);ce=t.mul(ce,Y),Y=t.add(M,K),ce=t.sub(ce,Y),Y=t.add(w,O);let ne=t.add(B,S);return Y=t.mul(Y,ne),ne=t.add(M,j),Y=t.sub(Y,ne),ne=t.add(T,O),E=t.add(y,S),ne=t.mul(ne,E),E=t.add(K,j),ne=t.sub(ne,E),k=t.mul(U,Y),E=t.mul(W,j),k=t.add(E,k),E=t.sub(K,k),k=t.add(K,k),I=t.mul(E,k),K=t.add(M,M),K=t.add(K,M),j=t.mul(U,j),Y=t.mul(W,Y),K=t.add(K,j),j=t.sub(M,j),j=t.mul(U,j),Y=t.add(Y,j),M=t.mul(K,Y),I=t.add(I,M),M=t.mul(ne,Y),E=t.mul(ce,E),E=t.sub(E,M),M=t.mul(ce,K),k=t.mul(ne,k),k=t.add(k,M),new D(E,I,k)}subtract(m){return this.add(m.negate())}is0(){return this.equals(D.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,O;const B=y=>F.cached(this,y,S=>mr(D,S));if(w){const{k1neg:y,k1:S,k2neg:E,k2:I}=G(m),{p:k,f:U}=B(S),{p:W,f:M}=B(I);O=U.add(M),T=H(w.beta,k,W,y,E)}else{const{p:y,f:S}=B(m);T=y,O=S}return mr(D,[T,O])[0]}multiplyUnsafe(m){const{endo:w}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ie||T.is0())return D.ZERO;if(m===Ye)return T;if(F.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:B,k2neg:y,k2:S}=G(m),{p1:E,p2:I}=_o(D,T,B,S);return H(w.beta,E,I,O,y)}else return F.unsafe(T,m)}toAffine(m){return q(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Ye?!0:m?m(D,this):F.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Ye?this:m?m(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return ft(m,"isCompressed"),this.assertValidity(),f(D,this,m)}toHex(m=!0){return et(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};C(D,"BASE",new D(i.Gx,i.Gy,t.ONE)),C(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),C(D,"Fp",t),C(D,"Fn",n);let X=D;const se=n.BITS,F=new go(X,e.endo?Math.ceil(se/2):se);return X.BASE.precompute(8),X}function Rr(r){return Uint8Array.of(r?2:3)}function kr(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function vo(r,e={}){const{Fn:s}=r,t=e.randomBytes||Qs,n=Object.assign(kr(r.Fp,s),{seed:xr(s.ORDER)});function i(f){try{const g=s.fromBytes(f);return s.isValidNot0(g)}catch{return!1}}function o(f,g){const{publicKey:b,publicKeyUncompressed:v}=n;try{const A=f.length;return g===!0&&A!==b||g===!1&&A!==v?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return fo(V(f,n.seed,"seed"),s.ORDER)}function c(f,g=!0){return r.BASE.multiply(s.fromBytes(f)).toBytes(g)}function l(f){const{secretKey:g,publicKey:b,publicKeyUncompressed:v}=n;if(!Ft(f)||"_lengths"in s&&s._lengths||g===b)return;const A=V(f,void 0,"key").length;return A===b||A===v}function u(f,g,b=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(g)===!1)throw new Error("second arg must be public key");const v=s.fromBytes(f);return r.fromBytes(g).multiply(v).toBytes(b)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},x=mo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,Point:r,utils:p,lengths:n})}function Eo(r,e,s={}){zs(e),Vt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Qs,n=s.hmac||((m,w)=>Ar(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:x,lengths:f}=vo(r,s),g={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*Tr<i.ORDER;function v(m){const w=a>>Ye;return m>w}function A(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function R(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function L(m,w){Xt(w);const T=f.signature,O=w==="compact"?T:w==="recovered"?T+1:void 0;return V(m,O)}class P{constructor(w,T,O){C(this,"r");C(this,"s");C(this,"recovery");if(this.r=A("r",w),this.s=A("s",T),O!=null){if(R(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,T=g.format){L(w,T);let O;if(T==="der"){const{r:E,s:I}=Ne.toSig(V(w));return new P(E,I)}T==="recovered"&&(O=w[0],T="compact",w=w.subarray(1));const B=f.signature/2,y=w.subarray(0,B),S=w.subarray(B,B*2);return new P(o.fromBytes(y),o.fromBytes(S),O)}static fromHex(w,T){return this.fromBytes(ht(w),T)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new P(this.r,this.s,w)}recoverPublicKey(w){const{r:T,s:O}=this,B=this.assertRecovery(),y=B===2||B===3?T+a:T;if(!i.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const S=i.toBytes(y),E=r.fromBytes(ke(Rr((B&1)===0),S)),I=o.inv(y),k=q(V(w,void 0,"msgHash")),U=o.create(-k*I),W=o.create(O*I),M=r.BASE.multiplyUnsafe(U).add(E.multiplyUnsafe(W));if(M.is0())throw new Error("invalid recovery: point at infinify");return M.assertValidity(),M}hasHighS(){return v(this.s)}toBytes(w=g.format){if(Xt(w),w==="der")return ht(Ne.hexFromSig(this));const{r:T,s:O}=this,B=o.toBytes(T),y=o.toBytes(O);return w==="recovered"?(R(),ke(Uint8Array.of(this.assertRecovery()),B,y)):ke(B,y)}toHex(w){return et(this.toBytes(w))}}const G=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const T=_t(w),O=w.length*8-c;return O>0?T>>BigInt(O):T},q=s.bits2int_modN||function(w){return o.create(G(w))},te=qt(c);function H(m){return eo("num < 2^"+c,m,Ie,te),o.toBytes(m)}function X(m,w){return V(m,void 0,"message"),w?V(e(m),void 0,"prehashed message"):m}function se(m,w,T){const{lowS:O,prehash:B,extraEntropy:y}=Zt(T,g);m=X(m,B);const S=q(m),E=o.fromBytes(w);if(!o.isValidNot0(E))throw new Error("invalid private key");const I=[H(E),H(S)];if(y!=null&&y!==!1){const M=y===!0?t(f.secretKey):y;I.push(V(M,void 0,"extraEntropy"))}const k=ke(...I),U=S;function W(M){const K=G(M);if(!o.isValidNot0(K))return;const j=o.inv(K),ce=r.BASE.multiply(K).toAffine(),Y=o.create(ce.x);if(Y===Ie)return;const ne=o.create(j*o.create(U+Y*E));if(ne===Ie)return;let en=(ce.x===Y?0:2)|Number(ce.y&Ye),tn=ne;return O&&v(ne)&&(tn=o.neg(ne),en^=1),new P(Y,tn,b?void 0:en)}return{seed:k,k2sig:W}}function F(m,w,T={}){const{seed:O,k2sig:B}=se(m,w,T);return so(e.outputLen,o.BYTES,n)(O,B).toBytes(T.format)}function D(m,w,T,O={}){const{lowS:B,prehash:y,format:S}=Zt(O,g);if(T=V(T,void 0,"publicKey"),w=X(w,y),!Ft(m)){const E=m instanceof P?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}L(m,S);try{const E=P.fromBytes(m,S),I=r.fromBytes(T);if(B&&E.hasHighS())return!1;const{r:k,s:U}=E,W=q(w),M=o.inv(U),K=o.create(W*M),j=o.create(k*M),ce=r.BASE.multiplyUnsafe(K).add(I.multiplyUnsafe(j));return ce.is0()?!1:o.create(ce.x)===k}catch{return!1}}function $(m,w,T={}){const{prehash:O}=Zt(T,g);return w=X(w,O),P.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:x,lengths:f,Point:r,sign:F,verify:D,recoverPublicKey:$,Signature:P,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Qt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ao={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Or=BigInt(2);function Io(r){const e=Qt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,p=le(u,s,e)*u%e,x=le(p,s,e)*u%e,f=le(x,Or,e)*l%e,g=le(f,n,e)*f%e,b=le(g,i,e)*g%e,v=le(b,a,e)*b%e,A=le(v,c,e)*v%e,R=le(A,a,e)*b%e,L=le(R,s,e)*u%e,P=le(L,o,e)*g%e,G=le(P,t,e)*l%e,q=le(G,Or,e);if(!es.eql(es.sqr(q),r))throw new Error("Cannot find square root");return q}const es=mt(Qt.p,{sqrt:Io}),To=Eo(So(Qt,{Fp:es,endo:Ao}),Xi),Ro=BigInt(0),tt=BigInt(1),ko=BigInt(2),Oo=BigInt(7),Co=BigInt(256),No=BigInt(113),Cr=[],Nr=[],Pr=[];for(let r=0,e=tt,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Cr.push(2*(5*t+s)),Nr.push((r+1)*(r+2)/2%64);let n=Ro;for(let i=0;i<7;i++)e=(e<<tt^(e>>Oo)*No)%Co,e&ko&&(n^=tt<<(tt<<BigInt(i))-tt);Pr.push(n)}const Lr=Gi(Pr,!0),Po=Lr[0],Lo=Lr[1],Dr=(r,e,s)=>s>32?Vi(r,e,s):Ki(r,e,s),Mr=(r,e,s)=>s>32?zi(r,e,s):qi(r,e,s);function Do(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],p=Dr(l,u,1)^s[a],x=Mr(l,u,1)^s[a+1];for(let f=0;f<50;f+=10)r[o+f]^=p,r[o+f+1]^=x}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=Nr[o],c=Dr(n,i,a),l=Mr(n,i,a),u=Cr[o];n=r[u],i=r[u+1],r[u]=c,r[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Po[t],r[1]^=Lo[t]}ze(s)}class ts{constructor(e,s,t,n=!1,i=24){C(this,"state");C(this,"pos",0);C(this,"posOut",0);C(this,"finished",!1);C(this,"state32");C(this,"destroyed",!1);C(this,"blockLen");C(this,"suffix");C(this,"outputLen");C(this,"enableXOF",!1);C(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,Ee(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Pi(this.state)}clone(){return this._cloneInto()}keccak(){Ys(this.state32),Do(this.state32,this.rounds),Ys(this.state32),this.posOut=0,this.pos=0}update(e){Ve(this),V(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ve(this,!1),V(e),this.finish();const s=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(s.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 Ee(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Js(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,ze(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new ts(s,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 Br=((r,e,s,t={})=>Zs(()=>new ts(e,r,s),t))(1,136,32),Mo=60;class Bo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Oi(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Mo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await bi(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ni(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
6
- ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Br(i),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=$o(a),l=c.slice(0,32),u=c.slice(32,64),p=c[64],x=p>=27?p-27:p,b=new To.Signature($r(l),$r(u)).addRecoveryBit(x).recoverPublicKey(o).toBytes(!1).slice(1),v=Br(b);return"0x"+et(v.slice(12))}}function $o(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function $r(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const Wo=3e4,Fo=1e3;class Uo{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,Fo*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??Wo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Ho=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Me{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=Me.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Me.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,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=Me.generateRandom16Hex(),l=Me.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const x=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const f=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),P(),t(new Error("Authentication timeout"))},5*60*1e3),g=10,b=30;let v=0,A=null;const R=()=>{clearInterval(L),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+b+"초간 대기합니다"),A=setTimeout(()=>{P(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},b*1e3)},L=setInterval(()=>{v++;try{x.closed&&(v<=g?R():(P(),t(new Error("로그인이 취소되었습니다"))))}catch{R()}},1e3),P=()=>{clearTimeout(f),clearInterval(L),A&&clearTimeout(A),window.removeEventListener("message",G)},G=q=>{if(q.origin!==e.expectedOrigin)return;if(!Ho.has(q.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",q.origin),P(),t(new Error("Unauthorized OAuth origin"));return}P();const te=typeof q.data.status=="string",H=te?q.data.data??{}:q.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:te?"wrapped":"flat",status:te?q.data.status:"(flat)"});const X=(H==null?void 0:H.state)??q.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(te&&q.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",H==null?void 0:H.error),t(new Error((H==null?void 0:H.error)||"Authentication failed"));return}if(!te&&(H!=null&&H.error)){d.error("[CROSSx] OAuth 실패:",H.error),t(new Error(H.error||"Authentication failed"));return}const se=H==null?void 0:H.idToken,F=H==null?void 0:H.accessToken,D=F??se,$=(H==null?void 0:H.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!F,hasIdToken:!!se,hasEmail:!!$}),!D){d.error("[CROSSx] 토큰을 찾을 수 없음:",q.data),t(new Error("Token not found in response"));return}const m={token:D,email:$},w=T=>{Me.verifyIdTokenNonce(T,l).then(()=>s(m)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};F?F.split(".").length===3?w(F):se?w(se):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):se?w(se):t(new Error("Token not found in response"))};window.addEventListener("message",G)})}}const st="crossx_wallet_data",je="crossx_mock_pin_hash";class Go{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(st)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(st);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(st,n);const i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(je,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new _(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(st);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(je);return s&&s!==e?!1:(s||await this.storage.set(je,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(d.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(je);if(n&&t&&n!==t)throw new _(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(je,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),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:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(st,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(je,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Be{constructor(e,s,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(bs))return e;const s=!e||this.tokenStore.isExpiringSoon(bs);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,s,t,n=!1){var c,l,u,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const f=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(f&&typeof f.code=="number"){if(f.code<0||f.code>=400){const g=f.message||f.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:f.code,message:g,url:o,method:e});const b=Be.mapGatewayError(f.code,f.data);if(b===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(b===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new _(h.USER_NOT_FOUND,Be.getGatewayErrorMessage(f.code,g));const v=b===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:b,A=v===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Be.getGatewayErrorMessage(f.code,g),R=f.data;let L;throw b===h.PIN_LOCKED?L=Be.extractLockDetails(R):b===h.ADDRESS_LIMIT_EXCEEDED?L={limit:Rt,raw:R}:L=R??void 0,new _(v,A,L)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:f.code,url:o,method:e}),f.data??f}return f}catch(x){if(x instanceof _)throw x;const f=((l=x.response)==null?void 0:l.status)??x.status;if((f===401||f===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${f} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=x.response)!=null&&u.data){const g=x.response.data,b=g.message||g.data||"API 요청에 실패했습니다",v=g.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:v,message:b,url:o,method:e,status:(p=x.response)==null?void 0:p.status}),new _(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${v}): ${b}`)}throw x}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new _(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new _(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new _(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.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,s,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:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,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(s)}`,a);return{chainId:s,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,s,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(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);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,s){const t={password:this.requirePin(),newPassword:s};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,s){const t={recoveryPin:e,sub:s};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 s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10036:return h.ADDRESS_LIMIT_EXCEEDED;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return Be.hasLockInfo(s)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){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 (${s}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${Rt} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class Ko{constructor(e,s,t){this.inner=e,this.getBridge=s,this.isAuthenticatedViaRNBridge=t,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(n,i)=>e.prepare(n,i)),e.migrateWallet&&(this.migrateWallet=(n,i)=>e.migrateWallet(n,i)),e.verifyPin&&(this.verifyPin=n=>e.verifyPin(n)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(n,i)=>e.verifyRecoveryPin(n,i))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,s,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){const c=await a.signMessage({chainId:s,message:t,from:o,index:n});return{chainId:s,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,s,t,n,i,o)}async signTypedData(e,s,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){const c=await a.signTypedData({chainId:s,typedData:t,from:o,index:n});return{chainId:s,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,s,t,n,i,o)}async signTransaction(e,s,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){const a=await o.signTransaction({chainId:s,tx:this.toBridgeTx(t),from:t.from,index:n});return{chainId:s,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,s,t,n,i)}async sendTransaction(e,s,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return{txHash:(await i.sendTransaction({chainId:s,tx:this.toBridgeTx(t),from:t.from})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,s,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,s){return this.inner.getAddress(e,s)}setOnUnauthorized(e){var s,t;(t=(s=this.inner).setOnUnauthorized)==null||t.call(s,e)}setTokenRefresher(e){var s,t;(t=(s=this.inner).setTokenRefresher)==null||t.call(s,e)}}class rt{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this._fetchPromise=null,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}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 s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=rt.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?bn:yn;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}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 s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new _(rt.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=rt.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new _(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(nt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Wr="__crossx-confirm-style",ee="__crossx-confirm-overlay",qo={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function Fr(r,e){const s=qo[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const Vo=`
6
+ For security, you must continue with the same account.`,session_alert_title:"Session expired",session_alert_account_label:"Account",session_alert_apple_account:"Apple account",session_alert_sign_out_button:"Sign out",session_alert_sign_in_again_button:"Sign in again"},un={ko:dn,en:fr};function be(s="en",e){return un[s]??fr}function hn(s){return s==="ko"||s==="en"?s:typeof navigator<"u"&&(navigator.language??"").toLowerCase().startsWith("ko")?"ko":"en"}const _r="crossx_access_token",gr="crossx_refresh_token",xr="crossx_user_info",Et=class Et{constructor(e,r,t,n,i,o,a,c,l=()=>{}){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this.requestFreshTokenFromBridge=c,this.getLocale=l,this._refreshPromise=null,this._migrated=!1;const u=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${u}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${u}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${u}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}setFreshTokenCallback(e){this.requestFreshTokenFromBridge=e}async hasValidStoredAccessToken(){try{const e=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN);if(!e)return!1;const r=this.crypto.decodeJWT(e);return r!=null&&r.exp?r.exp*1e3>Date.now():!1}catch{return!1}}async hasStoredRNBridgeSession(){if(!await this.hasValidStoredAccessToken())return!1;try{return!await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN)}catch{return!1}}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new _(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=hn(this.getLocale()),c=`${o}${i}`,l=c.includes("?")?"&":"?",u=`${c}${l}locale=${a}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`),d.log(`[CROSSx] Auth URL: ${u}`);const p=await this.oauth.openAuth({authUrl:u,expectedOrigin:new URL(o).origin});r=p.token,t=p.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new _(h.OAUTH_POPUP_BLOCKED,i):new _(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async executeWithNativeFirebaseIdToken(e){return d.log("[CROSSx] RN Bridge Firebase token 처리 (length:",e.idToken.length,")"),this.processNativeFirebaseToken(e)}async processNativeFirebaseToken(e){var t,n,i;let r;try{const{authApiUrl:o}=this.config,{accessToken:a}=await this.exchangeNativeFirebaseToken(e.idToken,o);let c,l;try{const u=this.crypto.decodeJWT(e.idToken);l=e.provider??((t=u.firebase)==null?void 0:t.sign_in_provider);const p=((n=u.firebase)==null?void 0:n.identities)??{};c=u.email??((i=p.email)==null?void 0:i[0]),d.log("[CROSSx] RN Bridge Firebase token 정보 — provider:",l,"email:",c??"(없음)")}catch{d.warn("[CROSSx] RN Bridge Firebase token에서 정보 추출 실패")}if(a){const u=await this.crypto.verifyJWT(a);if(!u.valid)throw new _(h.AUTH_FAILED,"Access token 검증 실패");const p=u.payload;r={id:p.sub,email:p.email??c,signInProvider:l,providerSub:e.providerSub},this.tokenStore.set(a),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,a),d.log("[CROSSx] RN Bridge — access_token 저장 (refresh_token 제외)")),d.log("[CROSSx] 사용자 정보 — id:",r.id,"email:",r.email??"(없음)"),await this.storage.set(this.STORAGE_KEY_USER,r)}else throw new _(h.AUTH_FAILED,"Access token 교환 실패")}catch(o){const a=o instanceof Error?o.message:String(o),c=o instanceof Error?o.stack:void 0,l=o instanceof Error?o.name:"UnknownError";return d.error("[CROSSx] RN Bridge 로그인 실패 — name:",l,"message:",a,"stack:",c),{success:!1,error:a||"RN Bridge login failed"}}return d.log("[CROSSx] RN Bridge 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,!1)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:p,refreshToken:g}=await this.exchangeFirebaseToken(e,u);let f,x,w;try{const I=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),x=(i=I.firebase)==null?void 0:i.sign_in_provider;const C=((o=I.firebase)==null?void 0:o.identities)??{};w=I.email??((a=C.email)==null?void 0:a[0]),x==="google.com"?f=(c=C["google.com"])==null?void 0:c[0]:x==="apple.com"&&(f=(l=C["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!f,"email:",w??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const I=this.crypto.decodeJWT(p);d.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const C=await this.crypto.verifyJWT(p);if(n=C.signatureVerified??!1,!C.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const k=C.payload,L=k.email??w??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",k.email??"(없음)","/ Firebase JWT:",w??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:k.sub,email:L,signInProvider:x,providerSub:f},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,p),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??r,signInProvider:x,providerSub:f},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const E=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,E),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeNativeFirebaseToken(e,r){const t=`${r}/cross-auth/social/login`;d.log("[CROSSx] RN Bridge Firebase 토큰 교환 요청 — url:",t,"projectId:",this.config.projectId);let n;try{n=await this.transport.request({url:t,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"}})}catch(a){d.error("[CROSSx] RN Bridge 토큰 교환 fetch 실패 — url:",t,"error:",a);const c=a instanceof Error?a.message:String(a);throw new _(h.AUTH_FAILED,`RN Bridge 토큰 교환 네트워크 실패: ${c}`,a)}d.log("[CROSSx] RN Bridge 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"RN Bridge token exchange");const o=this.extractAccessToken(i);if(!o)throw new _(h.AUTH_FAILED,"RN Bridge 토큰 교환 응답에서 access_token을 찾을 수 없습니다");return d.log("[CROSSx] RN Bridge access_token 교환 성공 (refresh_token 미저장)"),{accessToken:o}}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),n){t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}else{if(!t)return d.log("[CROSSx] restoreSession — refresh_token 및 access_token 없음, 세션 복원 생략"),null;if(!(await this.crypto.verifyJWT(t)).valid)return d.log("[CROSSx] restoreSession — refresh_token 없음, access_token도 invalid, 세션 복원 생략"),null;d.log("[CROSSx] restoreSession — refresh_token 없음, access_token만으로 복원 (RN Bridge 모드)"),this.tokenStore.set(t)}}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof _&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=Et.REFRESH_RELOGIN_CODES.has(c.code);throw new _(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new _(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.requestFreshTokenFromBridge){d.log("[CROSSx] RN Bridge access token 갱신 시도");try{const t=await this.requestFreshTokenFromBridge(),{accessToken:n}=await this.exchangeNativeFirebaseToken(t.idToken,this.config.authApiUrl);return n?(this.tokenStore.set(n),await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,n),d.log("[CROSSx] RN Bridge access token 갱신 성공"),!0):!1}catch(t){throw t instanceof _&&t.code===h.RN_NATIVE_SESSION_EXPIRED&&(d.warn("[CROSSx] RN Native session expired — 재로그인 필요"),this.tokenStore.clear(),await this.storage.remove(this.STORAGE_KEY_USER)),t}}if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof _&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(xr);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(_r);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(gr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(xr),await this.storage.remove(_r),await this.storage.remove(gr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof _&&i.code===h.MIGRATION_BACKUP_EXISTS)d.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))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};Et.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let Tt=Et;class pn{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class fn{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new _(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Rt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class _n{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new _(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class gn{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 xn(){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 Se{constructor(e){this.config=e,this.context=null}static async waitForBridgeReady(e=5e3){const r=Date.now();for(;Date.now()-r<e;){if(window.__CROSSX_RN_BRIDGE_READY__===!0)return d.log("[RNBridge] Bridge is ready"),!0;await new Promise(n=>setTimeout(n,50))}return d.warn("[RNBridge] Bridge ready timeout after",e,"ms"),!1}static isAvailable(){if(typeof window>"u")return!1;const e=window.__crossxRNBridge;return!!(e!=null&&e.isInstalled)}static getBridge(){if(typeof window>"u")return;const e=window.__crossxRNBridge;return e&&e.isInstalled?e:void 0}async initialize(){if(await Se.waitForBridgeReady(5e3)||d.warn("[RNBridge] Bridge did not become ready in time"),this.bridge=Se.getBridge(),!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"RN Bridge not available in this environment");if(typeof this.bridge.handshake!="function")throw d.error("[RNBridge] Bridge.handshake is not a function",{handshake:typeof this.bridge.handshake,bridge:Object.keys(this.bridge)}),new _(h.AUTH_NOT_INITIALIZED,"RN Bridge handshake method not available");const r=await this.handshake();return this.context=r,d.log("[RNBridge] Bootstrap initialization complete",{activated:r.isActivated,ttl:`${r.absoluteTtlMs/1e3/60}min`}),r}async handshake(){if(!this.bridge)throw new _(h.AUTH_NOT_INITIALIZED,"Bridge not initialized");const e=xn(),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");return{isActivated:!0,absoluteTtlMs:n.absoluteTtlMs,idleTtlMs:n.idleTtlMs,protocolVersion:n.protocolVersion,activatedAt:Date.now(),walletAddress:n.walletAddress}}catch(n){throw d.error("[RNBridge] Handshake failed",n),new _(h.AUTH_FAILED,"Bridge handshake failed",n)}}async requestFirebaseIdToken(){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");try{const r=await this.bridge.requestFirebaseIdToken(),t=(r.expiresAt-Date.now())/1e3;if(t<60)throw new _(h.AUTH_TOKEN_EXPIRED,"Firebase ID token TTL too short",{ttlSeconds:t});return r}catch(r){if(r instanceof _)throw r;const t=r instanceof Error?r.message:String(r);throw t.includes("USER_REJECTED")||t.toLowerCase().includes("rejected")?new _(h.USER_REJECTED,"Firebase ID token request rejected by user",r):(d.error("[RNBridge] Firebase token request failed",r),new _(h.AUTH_FAILED,"Firebase token request failed",r))}}async requestFreshFirebaseIdToken(){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");try{const r=await this.bridge.requestFreshFirebaseIdToken();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:(d.error("[RNBridge] Fresh Firebase token request failed",r),new _(h.SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",r))}}getContext(){return this.context}isActive(){var t;return!(!((t=this.context)!=null&&t.isActivated)||Date.now()-this.context.activatedAt>this.context.absoluteTtlMs)}}var it={environment:"production"};const Fe={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://portrait.crosstoken.io"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1",portraitBaseUrl:"https://dev-portrait.crosstoken.io"}};function wn(s){const e=s.environment;return e&&e in Fe?Fe[e]:null}function wr(){try{if(typeof it<"u"){const s=typeof it=="string"?JSON.parse(it):it,e=wn(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in Fe)return Fe[s]}catch{}return Fe.production}const mn=2e3,mr=6e4,yn=1e3,bn=1e4,Sn="0x77359400",yr="0x3B9ACA00",br=130,kt=6,Sr=18,vr=3e4,vn=5*60*1e3,En=30*1e3,ot=100,An="crossx-sdk-js/2.2.0";function Er(s){let e=s.length;for(;e>0&&s.charCodeAt(e-1)===48;)e--;return s.slice(0,e)}function In(s,e=kt){if(!s||s==="0x0"||s==="0x")return"0";try{const r=BigInt(s);if(r===0n)return"0";const t=10n**BigInt(Sr),n=r/t,o=(r%t).toString().padStart(Sr,"0"),a=Er(o).slice(0,e);return a?`${n}.${a}`:`${n}`}catch{return"?"}}function at(s,e,r,t=kt){if(!(!s||s==="0x"||s==="0x0"))try{const n=BigInt(s);if(n===0n)return;const i=10n**BigInt(r),o=n/i,c=(n%i).toString().padStart(r,"0"),l=Er(c.slice(0,t));return`${l?`${o}.${l}`:`${o}`} ${e}`}catch{return}}function Tn(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!==br)throw new _(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${br} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function Rn(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 kn(s,e){const r=On(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 On(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 Ue{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),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.deps.pinStore.has()&&!e)return;e&&this.deps.pinStore.clear();const r=await this.deps.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.deps.pinStore.clear();else if(this.deps.pinStore.has())return;if(this.verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this.verifyPinMutex;return}let i,o;this.verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=be(this.deps.getLocale()??"en");try{if(typeof this.deps.walletProvider.verifyPin!="function"){const l=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.deps.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.deps.pinStore.set(l);try{return await this.deps.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.deps.pinStore.clear(),{ok:!1,error:a.pin_input_error})}catch(u){if(this.deps.pinStore.clear(),u instanceof _){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pin_input_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return Ue.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof _&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=be(this.deps.getLocale()??"en"),u=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:l.session_alert_title,message:l.alert_session_expired,email:u?this.deps.maskEmail(u,l.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const r=be(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof _){if(t=Ue.parsePinError(n,r),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.deps.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof _&&(t=Ue.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=Ue.parsePinError(e,r);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}}class Cn{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 Pn(s){return s==="google"||s==="apple"}class Nn{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=Pn(e.loginType)?{provider:e.loginType}:void 0;let i;try{i=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!i.success)return this.deps.clearAuthState(),i;const o=((r=i.user)==null?void 0:r.providerSub)??null,a=((t=i.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!o&&o===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=be(this.deps.getLocale()??"en");return await this.deps.showSessionAlert({title:l.session_alert_title,message:l.alert_different_account,email:e.userEmail?this.deps.maskEmail(e.userEmail,l.session_alert_apple_account):void 0})==="signin-again"?(this.deps.setRecoveringSession(!1),this.signInAgain()):(this.deps.clearAuthState(),{success:!1,error:"Different account signed in"})}this.deps.applyAuthResult(i);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),i}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(r){const t=be(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),i=n?this.deps.maskEmail(n,t.session_alert_apple_account):void 0;if(r instanceof _&&r.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_account_withdrawn,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(r instanceof _&&r.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_wallet_not_found,email:i})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),r}if(!(r instanceof _)||r.code!==h.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.deps.showSessionAlert({title:t.session_alert_title,message:t.alert_session_expired,email:i})==="signout")throw this.deps.clearAuthState(),new _(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new _(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Ln{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async loadWalletAfterAuth(e,r){const t=this.deps.getUserId();if(!t)return;const n=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",n),n!=="exists")return;const i=await this.deps.walletProvider.getAddresses(t);if(i.length>0){let a,c=!1;if(r){const l=i.find(u=>u.address.toLowerCase()===r.toLowerCase());l?a=l:(a={address:r,index:0},c=!0)}else e!==void 0?a=i.find(l=>l.index===e)??i[0]:a=i[0];c?d.log("[CROSSx] preferredWalletAddress 가 서버 캐시에 없음 — raw address 채택:",a.address):d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",a.address),this.deps.setActiveWallet(a.address,a.index);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.deps.pinOrchestrator.ensureVerifiedPin();const o=await this.deps.walletProvider.getAddress(t,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.deps.setActiveWallet(o.address,0)}}class Dn{constructor(e){this.deps=e}async handleMigrationFlow(e){var c,l;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=this.deps.getAllowSkip(),t=await this.deps.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(u===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const p=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!p){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(p.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const g=p.pinStatus;if(o=g.maxAttempts,i=o-g.remainingAttempts,g.remainingAttempts===0&&g.lockExpiresAt){const f=g.lockExpiresAt*1e3,x=Math.max(1,Math.round((f-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${w}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(p){if(!(p instanceof _))throw p;if(p.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const g=be(this.deps.getLocale()??"en"),f=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:g.session_alert_title,message:g.alert_session_expired,email:f?this.deps.maskEmail(f,g.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.deps.clearAuthState(),p}if(p.code===h.MIGRATION_PIN_LOCKED){const g=p.details;if(o=(g==null?void 0:g.maxAttempts)??5,(g==null?void 0:g.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.deps.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const f=((g==null?void 0:g.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((f-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(x,w),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",p),p}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof _&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof _&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const p=be(this.deps.getLocale()??"en"),g=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:p.session_alert_title,message:p.alert_session_expired,email:g?this.deps.maskEmail(g,p.session_alert_apple_account):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const w=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",w.address),w}catch(w){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",w),w}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class $n{constructor(e){this.deps=e}async withResolvedGasAndFee(e,r){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.deps.getActiveAddress()??void 0:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,p,g]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],r):null,i?this.deps.estimateGas(e,r):null,o?this.deps.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=p,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const f=g;if(f){const x=yr;c.maxFeePerGas=`0x${(BigInt(f)+BigInt(x)).toString(16)}`,c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Sn,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=yr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Mn{constructor(e){this.crypto=e}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Bn(s){return s?s.includes("google")?"google":s.includes("apple")?"apple":s:null}class Wn{constructor(e){this.deps=e}setActiveWallet(e,r,t){this.deps.setState({address:e,activeWalletIndex:r});const n={address:e,index:r};(t==null?void 0:t.walletName)!==void 0&&(n.walletName=t.walletName),this.deps.emitAddressChanged(n),this.deps.shouldPersistWalletPreference()&&this.deps.storage.set(this.deps.walletPreferenceKey,{index:r,address:e}).catch(()=>{})}applyAuthResult(e){var t,n,i,o,a;const r={authenticated:e.success,userId:((t=e.user)==null?void 0:t.id)??null,address:e.address??null,activeWalletIndex:0,userEmail:((n=e.user)==null?void 0:n.email)??null,providerSub:((i=e.user)==null?void 0:i.providerSub)??null,loginType:Bn((o=e.user)==null?void 0:o.signInProvider),tokenSignatureVerified:e.tokenSignatureVerified??!1};this.deps.setState(r),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:e.success,address:e.address??null,userId:((a=e.user)==null?void 0:a.id)??null})}clearAuthState(){this.deps.setState({authenticated:!1,userId:null,address:null,activeWalletIndex:0,userEmail:null,providerSub:null,loginType:null,tokenSignatureVerified:!1}),this.deps.pinStore.clear(),this.deps.shouldPersistWalletPreference()&&this.deps.storage.remove(this.deps.walletPreferenceKey).catch(()=>{}),this.deps.getIsRecoveringSession()||this.deps.emitAuthChanged({isAuthenticated:!1,address:null,userId:null})}}class Fn{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 Un{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 Hn{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const r=await this.deps.walletLifecycleService.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",r),r==="migration_required"){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",t);const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}return r==="exists"?(await this.deps.pinOrchestrator.ensureVerifiedPin(),this.tryGetOrCreateWalletWithMigrationFallback(e)):(await this.deps.pinOrchestrator.ensurePinSetup(),this.tryGetOrCreateWalletWithMigrationFallback(e))}async tryGetOrCreateWalletWithMigrationFallback(e){try{const r=await this.deps.pinOrchestrator.withPinRetry(()=>this.deps.walletProvider.getOrCreateWallet(e));return this.deps.setActiveWallet(r.address,0),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof _&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.deps.getProviderSub()??e;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.deps.migrationOrchestrator.handleMigrationFlow(t);if(n)return this.deps.setActiveWallet(n.address,0),{address:n.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}}function Ar(s,e){const r=s.replace(/\/$/,""),t=e.startsWith("/")?e:`/${e}`;return`${r}/cross-auth${t}`}class Gn{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=Ar(i,`/v2/token-historical/${e}/${n}`),a={clientVersion:t};try{d.log("[TokenHistory] Registering tx:",e,n);const c=await this.deps.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:a,retries:0});c.status!==200&&this.handleError(c.status,"register"),d.log("[TokenHistory] Successfully registered:",e,n)}catch(c){throw c instanceof _?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(Ar(r,"/v2/token-historical"));(e==null?void 0:e.lastTimestamp)!==void 0&&t.searchParams.append("last_timestamp",e.lastTimestamp.toString()),(e==null?void 0:e.lastTxIndex)!==void 0&&t.searchParams.append("last_tx_index",e.lastTxIndex.toString());try{d.log("[TokenHistory] Fetching token history");const i=await this.deps.transport.request({url:t.toString(),method:"GET",retries:0});if(i.status===404)throw new _(h.UNKNOWN_ERROR,"Transaction not found (404) — please retry");return i.status!==200&&this.handleError(i.status,"fetch"),d.log("[TokenHistory] Successfully fetched history:",((n=i.data.rows)==null?void 0:n.length)??0,"items"),i.data.rows||[]}catch(i){throw i instanceof _?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){d.log(`[TokenHistory] Retry ${a+1}/${i} (404 - tx not yet indexed)`),await new Promise(u=>setTimeout(u,o));continue}throw c}}handleError(e,r){const n={400:{code:h.TX_INVALID_PARAMS,message:`Bad request (400): ${r==="register"?"invalid params or unsupported transfer method":"invalid query params"}`},404:{code:h.UNKNOWN_ERROR,message:"Transaction not found (404) — please retry"},500:{code:h.UNKNOWN_ERROR,message:"Server error (500)"}}[e]||{code:h.UNKNOWN_ERROR,message:`HTTP ${e}`};throw new _(n.code,n.message)}}function Ot(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 Be=class Be extends gn{constructor(e,r,t,n,i,o,a,c,l,u,p){var g,f;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._rnBridgeService=null,this._providers=new Map,this._isAuthenticatedViaRNBridge=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&pr(e.logger),this.confirmation=l,this.pinStore=p??new Rt,this.stateManager=new Wn({setState:x=>{x.authenticated!==void 0&&(this.authenticated=x.authenticated),x.userId!==void 0&&(this.userId=x.userId),x.address!==void 0&&(this.address=x.address),x.activeWalletIndex!==void 0&&(this.activeWalletIndex=x.activeWalletIndex),x.userEmail!==void 0&&(this.userEmail=x.userEmail),x.providerSub!==void 0&&(this.providerSub=x.providerSub),x.loginType!==void 0&&(this.loginType=x.loginType),x.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=x.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:x,index:w,walletName:E})=>{const I={address:x,index:w};E!==void 0&&(I.walletName=E),this.emit("addressChanged",I)},emitAuthChanged:({isAuthenticated:x,address:w,userId:E})=>{this.emit("authChanged",{isAuthenticated:x,address:w,userId:E})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Be.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Ue({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Ot,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new Cn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,isRNBridgeMode:()=>this._isAuthenticatedViaRNBridge}),this.walletLifecycleService=new Ln({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(x,w)=>this.setActiveWallet(x,w)}),this.migrationOrchestrator=new Dn({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(x,w)=>this.migrateWalletUseCase.execute(x,w),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:Ot,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var x;return((x=this._config.migration)==null?void 0:x.allowSkip)??!0}}),this.transactionLifecycleService=new $n({getActiveAddress:()=>this.address,estimateGas:(x,w)=>this.estimateGas(x,w),getBaseFeePerGas:x=>this.getBaseFeePerGas(x),jsonRpcCall:(x,w,E)=>this.jsonRpc.call(x,w,E)}),this.signatureVerifier=new Mn(this.crypto),this.addressResolverService=new Fn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Un({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Hn({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(x,w)=>this.setActiveWallet(x,w)}),this.tokenHistoryService=new Gn({transport:i,getApiBaseUrl:()=>this.internalConfig.authApiUrl}),this.sessionOrchestrator=new Nn({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:Ot}),this.chainRegistry=u,this.jsonRpc=new _n(u,i),this.signInUseCase=new Tt(this.internalConfig,t,n,o,i,a,c,void 0,()=>this._config.locale),this.signOutUseCase=new pn(this.internalConfig,t,c),this.migrateWalletUseCase=new fn(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(f=a.setTokenRefresher)==null||f.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}isAuthenticatedViaRNBridge(){return this._isAuthenticatedViaRNBridge}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v2.2.0 초기화 중..."),this.confirmation.setMessages(be(this._config.locale));try{const n=wr();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=this._config.persistWalletPreference!==!1?await this.storage.get(Be.WALLET_PREF_KEY).catch(()=>null):null,o=(e==null?void 0:e.preferredWalletIndex)??(i==null?void 0:i.index);let a=(e==null?void 0:e.preferredWalletAddress)??(i==null?void 0:i.address),c=await this.tryRNBridgeBootstrap();if(this._rnBridgeWalletAddress&&((a==null?void 0:a.toLowerCase())!==this._rnBridgeWalletAddress.toLowerCase()&&d.log("[CROSSx] RN Bridge active wallet으로 preferredWalletAddress 갱신:",this._rnBridgeWalletAddress),a=this._rnBridgeWalletAddress),c||(c=await this.signInUseCase.restoreSession()),c!=null&&c.success)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,o??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(o,a)}catch(u){if(!(u instanceof _&&u.code===h.PIN_CANCELLED))throw u;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,d.info("[CROSSx SDK] v2.2.0 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new _(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async tryRNBridgeBootstrap(){if(!Se.isAvailable())return null;try{d.log("[CROSSx] RN Bridge 감지 — Handshake 시도");const e=new Se({appId:this._config.projectId,appVersion:"1.0.0",sdkVersion:"2.2.0",keyId:"key-id-1",userIdHash:"user-hash-placeholder",projectId:this._config.projectId}),r=await e.initialize();return this._rnBridgeService=e,this._rnBridgeWalletAddress=r.walletAddress,this.subscribeBridgeWalletChanged(),d.log("[CROSSx] RN Bridge Handshake 성공",{walletAddress:r.walletAddress??"(없음)"}),await this.signInUseCase.hasValidStoredAccessToken()?(await this.signInUseCase.hasStoredRNBridgeSession()&&(this._isAuthenticatedViaRNBridge=!0,d.log("[CROSSx] 저장된 RN Bridge 세션 — native sign delegation 활성")),null):(d.log("[CROSSx] RN Bridge 준비 완료 — 사용자 로그인 대기"),null)}catch(e){return d.warn("[CROSSx] RN Bridge handshake 실패",e),null}}async _tryBridgeSignIn(){var e;if(!this._rnBridgeService)return null;try{const r=await this._rnBridgeService.requestFirebaseIdToken();d.log("[CROSSx] Bridge 로그인 — Firebase token 수신");const t=await this.signInUseCase.executeWithNativeFirebaseIdToken(r);return t.success?(this._isAuthenticatedViaRNBridge=!0,this.applyAuthResult(t),await this.loadWalletAfterAuth(void 0,this._rnBridgeWalletAddress),d.log("[CROSSx] Bridge 로그인 성공",{userId:(e=t.user)==null?void 0:e.id}),t):null}catch(r){return r instanceof _&&r.code===h.USER_REJECTED?(d.log("[CROSSx] Bridge 로그인 거부 — bridge 비활성화, OAuth fallback"),this._rnBridgeService=null,null):(d.warn("[CROSSx] Bridge 로그인 타임아웃/실패 — OAuth fallback 차단",r),!1)}}async requestFreshFirebaseIdTokenFromBridge(){if(!this._rnBridgeService)throw new _(h.RN_BRIDGE_NOT_AVAILABLE,"RN Bridge not available");try{return await this._rnBridgeService.requestFreshFirebaseIdToken()}catch(e){throw d.error("[CROSSx] Fresh Firebase token request failed:",e),new _(h.RN_NATIVE_SESSION_EXPIRED,"Native session expired. Please sign in again in the app.",e)}}getRNBridge(){return Se.getBridge()}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");if(this._rnBridgeService){const t=await this._tryBridgeSignIn();if(t===!1)return{success:!1,error:"Bridge authentication timed out without user decision"};if(t!=null&&t.success)return t}let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:on(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new _(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");r={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof _?t:new _(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const{preferredWalletAddress:r,...t}=e??{},n=await this.signIn(t);if(!n.success)return{...n,addresses:[]};try{if(n.needsMigration||!n.address){const{address:a}=await this.createWallet(),c=await this.getAddresses(),l=await this.selectWalletIfMultiple(c,r);return{...n,address:(l==null?void 0:l.address)??a,needsMigration:!1,addresses:c}}const i=await this.getAddresses(),o=await this.selectWalletIfMultiple(i,r);return{...n,address:(o==null?void 0:o.address)??n.address,addresses:i}}catch(i){throw i instanceof _&&i.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),i}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithOAuthToken(e);return r.success&&this.applyAuthResult(r),r}catch(r){throw r instanceof _?r:new _(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",r)}}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.applyAuthResult(t),t}catch(t){throw t instanceof _?t:new _(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState();const e=Se.getBridge();if(e!=null&&e.signOut)try{await e.signOut(),d.log("[CROSSx] RN Bridge signOut 통보 완료 — native trust cache 무효화")}catch(r){d.warn("[CROSSx] RN Bridge signOut 통보 실패 (로그아웃 자체는 정상)",r)}this._rnBridgeService=null,this._rnBridgeWalletAddress=void 0,this._rnBridgeWalletName=void 0}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}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof _&&r.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified,data:{provider:this.loginType??void 0,accessToken:this.tokenStore.get()??"",email:this.userEmail??void 0,sub:this.userId,providerSub:this.providerSub??void 0}}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.setActiveWallet(r.address,0),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof _?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){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.pinOrchestrator.ensurePinForSigning();const n=r.length,o={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&this.setActiveWallet(t.address,t.index),t}async selectWalletIfMultiple(e,r){if(e.length<2)return null;if(r){const t=e.find(n=>n.address.toLowerCase()===r.toLowerCase());if(t)return this.setActiveWallet(t.address,t.index),t}return this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?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))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){return this.ensureAuthenticated(),this.walletCreationService.createWallet()}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const i=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the message signing request",prepareAction:"sign-message",prepareContext:{message:r,from:n.address},execute:o=>this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,o,n.address)});return this.signatureVerifier.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof _?i:new _(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");kn(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 Tn(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(Be.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=It(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 Rn(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=It(e);try{const o=await this.signingOrchestrator.confirmAndExecuteWithPreparedPin({confirmation:{type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName},rejectedMessage:"User rejected the transaction request",prepareAction:"send",prepareContext:{tx:n},execute:async u=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,u)).txHash;const p=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,u);return p.txHash??p.signature}}),a=(r.data??"").toLowerCase().replace(/^0x/,""),c=a===""||a==="00000000",l=a.startsWith("a9059cbb");return(c||l)&&this.tokenHistoryService.registerHistoryFireAndForget(e,o,An).catch(u=>d.log("[TokenHistory] register failed (non-critical):",u)),{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??yn,i=bn,o=t.timeoutMs??mr,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new _(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var w,E;if(this._isAuthenticatedViaRNBridge){const I=Se.getBridge();if(I!=null&&I.sendTransactionWithWaitForReceipt)return this.bridgeSendTransactionWithWaitForReceipt(I,e,r,t)}const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((w=this._config.receiptPolling)==null?void 0:w.intervalMs)??mn,l=i??((E=this._config.receiptPolling)==null?void 0:E.timeoutMs)??mr,u=It(e),p=r.from??"";let g,f;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{g=I;const C=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),k=r.value?BigInt(r.value):0n,L=at(r.value,u.symbol,u.decimals,this._config.displayDecimals),B=at("0x"+C.toString(16),u.symbol,u.decimals,this._config.displayDecimals),K=at("0x"+(k+C).toString(16),u.symbol,u.decimals,this._config.displayDecimals);return{chainId:e,txHash:a,from:I.from,to:I.to??r.to,amount:L,fees:B,total:K,nativeSymbol:u.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(f=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:p,to:r.to,amount:at(r.value,u.symbol,u.decimals,this._config.displayDecimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:p,to:r.to},x),f)throw f;return{chainId:e,txHash:a,receipt:g}}async bridgeSendTransactionWithWaitForReceipt(e,r,t,n){const i=await e.sendTransactionWithWaitForReceipt({chainId:r,tx:{to:t.to,value:t.value,data:t.data,gasLimit:t.gasLimit,gasPrice:t.gasPrice,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas,nonce:t.nonce},from:t.from,dappName:n.dappName,accountName:n.accountName,index:n.index,timeoutMs:n.timeoutMs,pollIntervalMs:n.intervalMs});return{chainId:r,txHash:i.txHash,receipt:{transactionHash:i.txHash,blockHash:i.blockHash??"",blockNumber:i.blockNumber??"",from:i.from??t.from??"",to:i.to??null,gasUsed:i.gasUsed??"0x0",effectiveGasPrice:i.effectiveGasPrice??"0x0",status:i.status==="0x0"?"0x0":"0x1",logs:[],transactionIndex:"0x0",type:"0x0"}}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}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),d.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){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:In(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 hr(this,e),this._providers.set(e,r)),r}emitAccountsChanged(e){this._providers.size!==0&&this._providers.forEach(r=>{try{r.emit("accountsChanged",[e])}catch(t){d.warn("[CROSSx] accountsChanged emit 중 listener 예외",t)}})}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof _)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=Se.getBridge();if(!(e!=null&&e.onEvent)){d.warn("[CROSSx] bridge.onEvent 미지원 — walletChanged 구독 불가");return}e.onEvent("walletChanged",r=>{if(!e.isInstalled){d.warn("[walletChanged] bridge 비활성 — 이벤트 무시");return}if(!r||typeof r!="object"){d.warn("[walletChanged] invalid payload — 이벤트 무시",r);return}const t=r,n=typeof t.address=="string"?t.address.trim():"";if(!/^0x[a-fA-F0-9]{40}$/.test(n)){d.warn("[walletChanged] invalid address — 이벤트 무시",t);return}if(t.source!=="rn-native-bridge"){d.warn("[walletChanged] invalid source — 이벤트 무시",t);return}const i=typeof t.walletName=="string"?t.walletName.trim():"",o=i.length>0&&i.length<=64?i:void 0;this.address&&this.address.toLowerCase()===n.toLowerCase()||(d.log("[CROSSx] Native walletChanged 수신",{address:n,walletId:t.walletId,source:t.source,walletName:o}),this.setActiveWallet(n,0,{walletName:o}),this._rnBridgeWalletAddress=n,this._rnBridgeWalletName=o)}),d.log("[CROSSx] bridge.onEvent walletChanged 구독 완료")}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState(),this._isAuthenticatedViaRNBridge=!1}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){return this.sessionOrchestrator.signInAgain()}async withSessionRecovery(e){return this.sessionOrchestrator.withSessionRecovery(e)}async loadWalletAfterAuth(e,r){return this.walletLifecycleService.loadWalletAfterAuth(e,r)}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(),pr(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Be.WALLET_PREF_KEY="wallet_preference",Be.OFFCHAIN_CHAIN_ID="0";let ct=Be;class Kn{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Ct="crossx-sdk",qn=1,_e="data",Ne="keys",lt="aes-primary",Vn=12;class Ir{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,qn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(_e)||i.createObjectStore(_e),i.objectStoreNames.contains(Ne)||i.createObjectStore(Ne)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,lt);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,lt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Ct)return null;try{const e=await this.openDB(Ct),r=e.transaction([Ne,_e],"readonly"),t=r.objectStore(Ne).get(lt),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(_e).getAll(),o=r.objectStore(_e).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ne,lt,n);for(let l=0;l<c.length;l++)await this.idbPut(_e,String(c[l]),a[l]);return indexedDB.deleteDatabase(Ct),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Vn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(_e,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(_e,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(_e,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(_e)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const Pt=crypto,Tr=s=>s instanceof CryptoKey,dt=new TextEncoder,Ze=new TextDecoder;function zn(...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 Jn=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Ze.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Jn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class ee 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)}}ee.code="ERR_JOSE_GENERIC";class de extends ee{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}}de.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Nt extends ee{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}}Nt.code="ERR_JWT_EXPIRED";class Rr extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}Rr.code="ERR_JOSE_ALG_NOT_ALLOWED";class ge extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}ge.code="ERR_JOSE_NOT_SUPPORTED";class jn extends ee{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}jn.code="ERR_JWE_DECRYPTION_FAILED";class Yn extends ee{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}Yn.code="ERR_JWE_INVALID";class Z extends ee{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Z.code="ERR_JWS_INVALID";class xe extends ee{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}xe.code="ERR_JWT_INVALID";class Xn extends ee{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}Xn.code="ERR_JWK_INVALID";class Lt extends ee{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Lt.code="ERR_JWKS_INVALID";class Dt extends ee{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Dt.code="ERR_JWKS_NO_MATCHING_KEY";class kr extends ee{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}kr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class Or extends ee{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}Or.code="ERR_JWKS_TIMEOUT";class Cr extends ee{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}Cr.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 Qe(s,e){return s.name===e}function $t(s){return parseInt(s.name.slice(4),10)}function Zn(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Qn(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 ei(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Qe(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Qe(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if($t(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Qe(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if($t(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(!Qe(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Qe(s.algorithm,"ECDSA"))throw we("ECDSA");const t=Zn(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Qn(s,r)}function Pr(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 Nr=(s,...e)=>Pr("Key must be ",s,...e);function Lr(s,e,...r){return Pr(`Key for the ${s} algorithm must be `,e,...r)}const Dr=s=>Tr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ut=["CryptoKey"],ti=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function ri(s){return typeof s=="object"&&s!==null}function ve(s){if(!ri(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const si=(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 He(s){return ve(s)&&typeof s.kty=="string"}function ni(s){return s.kty!=="oct"&&typeof s.d=="string"}function ii(s){return s.kty!=="oct"&&typeof s.d>"u"}function oi(s){return He(s)&&s.kty==="oct"&&typeof s.k=="string"}function ai(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 $r=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=ai(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,Pt.subtle.importKey("jwk",n,...t)},Mr=s=>Re(s);let Ge,Ke;const Br=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ht=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await $r({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},ci={normalizePublicKey:(s,e)=>{if(Br(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?Mr(r.k):(Ke||(Ke=new WeakMap),ht(Ke,s,r,e))}return He(s)?s.k?Re(s.k):(Ke||(Ke=new WeakMap),ht(Ke,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Br(s)){let r=s.export({format:"jwk"});return r.k?Mr(r.k):(Ge||(Ge=new WeakMap),ht(Ge,s,r,e))}return He(s)?s.k?Re(s.k):(Ge||(Ge=new WeakMap),ht(Ge,s,s,e,!0)):s}};async function Wr(s,e){if(!ve(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new ge('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return $r({...s,alg:e});default:throw new ge('Unsupported "kty" (Key Type) Parameter value')}}const qe=s=>s==null?void 0:s[Symbol.toStringTag],Mt=(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},li=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&He(e)){if(oi(e)&&Mt(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(!Dr(e))throw new TypeError(Lr(s,e,...ut,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${qe(e)} instances for symmetric algorithms must be of type "secret"`)}},di=(s,e,r,t)=>{if(t&&He(e))switch(r){case"sign":if(ni(e)&&Mt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(ii(e)&&Mt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Dr(e))throw new TypeError(Lr(s,e,...ut,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${qe(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${qe(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${qe(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${qe(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${qe(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Fr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?li(e,r,t,s):di(e,r,t,s)}Fr.bind(void 0,!1);const Ur=Fr.bind(void 0,!0);function ui(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 hi=(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 pi(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new ge(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function fi(s,e,r){if(e=await ci.normalizePublicKey(e,s),Tr(e))return ei(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(Nr(e,...ut));return Pt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(Nr(e,...ut,"Uint8Array","JSON Web Key"))}const _i=async(s,e,r,t)=>{const n=await fi(s,e,"verify");si(s,n);const i=pi(s,n.algorithm);try{return await Pt.subtle.verify(i,n,r,t)}catch{return!1}};async function gi(s,e,r){if(!ve(s))throw new Z("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new Z("JWS Protected Header incorrect type");if(s.payload===void 0)throw new Z("JWS Payload missing");if(typeof s.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(s.header!==void 0&&!ve(s.header))throw new Z("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const w=Re(s.protected);t=JSON.parse(Ze.decode(w))}catch{throw new Z("JWS Protected Header is invalid")}if(!ti(t,s.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=ui(Z,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 Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&hi("algorithms",r.algorithms);if(c&&!c.has(a))throw new Rr('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Ur(a,e,"verify"),He(e)&&(e=await Wr(e,a))):Ur(a,e,"verify");const u=zn(dt.encode(s.protected??""),dt.encode("."),typeof s.payload=="string"?dt.encode(s.payload):s.payload);let p;try{p=Re(s.signature)}catch{throw new Z("Failed to base64url decode the signature")}if(!await _i(a,e,p,u))throw new Cr;let f;if(o)try{f=Re(s.payload)}catch{throw new Z("Failed to base64url decode the payload")}else typeof s.payload=="string"?f=dt.encode(s.payload):f=s.payload;const x={payload:f};return s.protected!==void 0&&(x.protectedHeader=t),s.header!==void 0&&(x.unprotectedHeader=s.header),l?{...x,key:e}:x}async function xi(s,e,r){if(s instanceof Uint8Array&&(s=Ze.decode(s)),typeof s!="string")throw new Z("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new Z("Invalid Compact JWS");const a=await gi({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 wi=s=>Math.floor(s.getTime()/1e3),Hr=60,Gr=Hr*60,Bt=Gr*24,mi=Bt*7,yi=Bt*365.25,bi=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Kr=s=>{const e=bi.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*Hr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Gr);break;case"day":case"days":case"d":n=Math.round(r*Bt);break;case"week":case"weeks":case"w":n=Math.round(r*mi);break;default:n=Math.round(r*yi);break}return e[1]==="-"||e[4]==="ago"?-n:n},qr=s=>s.toLowerCase().replace(/^application\//,""),Si=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,vi=(s,e,r={})=>{let t;try{t=JSON.parse(Ze.decode(e))}catch{}if(!ve(t))throw new xe("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||qr(s.typ)!==qr(n)))throw new de('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const x of new Set(u.reverse()))if(!(x in t))throw new de(`missing required "${x}" claim`,t,x,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new de('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new de('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Si(t.aud,typeof c=="string"?[c]:c))throw new de('unexpected "aud" claim value',t,"aud","check_failed");let p;switch(typeof r.clockTolerance){case"string":p=Kr(r.clockTolerance);break;case"number":p=r.clockTolerance;break;case"undefined":p=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=r,f=wi(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new de('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new de('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>f+p)throw new de('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new de('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=f-p)throw new Nt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=f-t.iat,w=typeof l=="number"?l:Kr(l);if(x-p>w)throw new Nt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-p)throw new de('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Ei(s,e,r){var o;const t=await xi(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:vi(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Ai(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 Ii(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Ti)}function Ti(s){return ve(s)}function Vr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Ri{constructor(e){if(this._cached=new WeakMap,!Ii(e))throw new Lt("JSON Web Key Set malformed");this._jwks=Vr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Ai(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Dt;if(c!==1){const l=new kr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const p of o)try{yield await zr(u,p,t)}catch{}},l}return zr(this._cached,a,t)}}async function zr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Wr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new Lt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function Jr(s){const e=new Ri(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Vr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const ki=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 Or:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new ee("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new ee("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Oi(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Wt;(typeof navigator>"u"||!((tn=(At=navigator.userAgent)==null?void 0:At.startsWith)!=null&&tn.call(At,"Mozilla/5.0 ")))&&(Wt="jose/v5.10.0");const Ft=Symbol();function Ci(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!ve(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,ve))}class Pi{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[Ft])!==void 0&&(this._cache=r==null?void 0:r[Ft],Ci(r==null?void 0:r[Ft],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Jr(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 Dt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Oi()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Wt&&!e.has("User-Agent")&&(e.set("User-Agent",Wt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=ki(this._url,this._timeoutDuration,this._options).then(r=>{this._local=Jr(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 Ni(s,e){const r=new Pi(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 Li=Re;function Di(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=Li(e)}catch{throw new xe("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Ze.decode(t))}catch{throw new xe("Failed to parse the decoded payload as JSON")}if(!ve(n))throw new xe("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ut(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ee(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function V(s,e,r=""){const t=Ut(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 jr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ee(s.outputLen),Ee(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 Yr(s,e){V(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 $i(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function ze(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ht(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const Mi=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Bi(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Wi(s){for(let e=0;e<s.length;e++)s[e]=Bi(s[e]);return s}const Xr=Mi?s=>s:Wi,Zr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fi=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function et(s){if(V(s),Zr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Fi[s[r]];return e}const Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Qr(s){if(s>=Ae._0&&s<=Ae._9)return s-Ae._0;if(s>=Ae.A&&s<=Ae.F)return s-(Ae.A-10);if(s>=Ae.a&&s<=Ae.f)return s-(Ae.a-10)}function pt(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Zr)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=Qr(s.charCodeAt(i)),a=Qr(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];V(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 es(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 ts(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 Ui=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Hi(s,e,r){return s&e^~s&r}function Gi(s,e,r){return s&e^s&r^e&r}class Ki{constructor(e,r,t,n){N(this,"blockLen");N(this,"outputLen");N(this,"padOffset");N(this,"isLE");N(this,"buffer");N(this,"view");N(this,"finished",!1);N(this,"length",0);N(this,"pos",0);N(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ht(this.buffer)}update(e){Ve(this),V(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=Ht(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){Ve(this),Yr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,ze(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=Ht(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<l;p++)a.setUint32(4*p,u[p],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ft=BigInt(2**32-1),rs=BigInt(32);function qi(s,e=!1){return e?{h:Number(s&ft),l:Number(s>>rs&ft)}:{h:Number(s>>rs&ft)|0,l:Number(s&ft)|0}}function Vi(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}=qi(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const zi=(s,e,r)=>s<<r|e>>>32-r,Ji=(s,e,r)=>e<<r|s>>>32-r,ji=(s,e,r)=>e<<r-32|s>>>64-r,Yi=(s,e,r)=>s<<r-32|e>>>64-r,Xi=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]),Ce=new Uint32Array(64);class Zi extends Ki{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)Ce[p]=e.getUint32(r,!1);for(let p=16;p<64;p++){const g=Ce[p-15],f=Ce[p-2],x=me(g,7)^me(g,18)^g>>>3,w=me(f,17)^me(f,19)^f>>>10;Ce[p]=w+Ce[p-7]+x+Ce[p-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let p=0;p<64;p++){const g=me(a,6)^me(a,11)^me(a,25),f=u+g+Hi(a,c,l)+Xi[p]+Ce[p]|0,w=(me(t,2)^me(t,13)^me(t,22))+Gi(t,n,i)|0;u=l,l=c,c=a,a=o+f|0,o=i,i=n,n=t,t=f+w|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){ze(Ce)}destroy(){this.set(0,0,0,0,0,0,0,0),ze(this.buffer)}}class Qi extends Zi{constructor(){super(32);N(this,"A",Oe[0]|0);N(this,"B",Oe[1]|0);N(this,"C",Oe[2]|0);N(this,"D",Oe[3]|0);N(this,"E",Oe[4]|0);N(this,"F",Oe[5]|0);N(this,"G",Oe[6]|0);N(this,"H",Oe[7]|0)}}const eo=es(()=>new Qi,Ui(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gt=BigInt(0),Kt=BigInt(1);function _t(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function ss(s){if(typeof s=="bigint"){if(!wt(s))throw new Error("positive bigint expected, got "+s)}else Ee(s);return s}function gt(s){const e=ss(s).toString(16);return e.length&1?"0"+e:e}function ns(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Gt:BigInt("0x"+s)}function xt(s){return ns(et(s))}function is(s){return ns(et(to(V(s)).reverse()))}function qt(s,e){Ee(e),s=ss(s);const r=pt(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function os(s,e){return qt(s,e).reverse()}function to(s){return Uint8Array.from(s)}const wt=s=>typeof s=="bigint"&&Gt<=s;function ro(s,e,r){return wt(s)&&wt(e)&&wt(r)&&e<=s&&s<r}function so(s,e,r,t){if(!ro(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function no(s){let e;for(e=0;s>Gt;s>>=Kt,e+=1);return e}const Vt=s=>(Kt<<BigInt(s))-Kt;function io(s,e,r){if(Ee(s,"hashLen"),Ee(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=E=>new Uint8Array(E),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const p=()=>{c.fill(1),l.fill(0),u=0},g=(...E)=>r(l,ke(c,...E)),f=(E=n)=>{l=g(i,E),c=g(),E.length!==0&&(l=g(o,E),c=g())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let E=0;const I=[];for(;E<e;){c=g();const C=c.slice();I.push(C),E+=c.length}return ke(...I)};return(E,I)=>{p(),f(E);let C;for(;!(C=I(x()));)f();return p(),C}}function zt(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 as(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 ie=BigInt(0),se=BigInt(1),Le=BigInt(2),cs=BigInt(3),ls=BigInt(4),ds=BigInt(5),oo=BigInt(7),us=BigInt(8),ao=BigInt(9),hs=BigInt(16);function ue(s,e){const r=s%e;return r>=ie?r:e+r}function le(s,e,r){let t=s;for(;e-- >ie;)t*=t,t%=r;return t}function ps(s,e){if(s===ie)throw new Error("invert: expected non-zero number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let r=ue(s,e),t=e,n=ie,i=se;for(;r!==ie;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==se)throw new Error("invert: does not exist");return ue(n,e)}function Jt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function fs(s,e){const r=(s.ORDER+se)/ls,t=s.pow(e,r);return Jt(s,t,e),t}function co(s,e){const r=(s.ORDER-ds)/us,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return Jt(s,a,e),a}function lo(s){const e=mt(s),r=_s(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+oo)/hs;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const p=a.mul(l,n),g=a.mul(l,i),f=a.eql(a.sqr(u),c),x=a.eql(a.sqr(p),c);l=a.cmov(l,u,f),u=a.cmov(g,p,x);const w=a.eql(a.sqr(u),c),E=a.cmov(l,u,w);return Jt(a,E,c),E}}function _s(s){if(s<cs)throw new Error("sqrt is not defined for small field");let e=s-se,r=0;for(;e%Le===ie;)e/=Le,r++;let t=Le;const n=mt(s);for(;xs(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return fs;let i=n.pow(t,e);const o=(e+se)/Le;return function(c,l){if(c.is0(l))return l;if(xs(c,l)!==1)throw new Error("Cannot find square root");let u=r,p=c.mul(c.ONE,i),g=c.pow(l,e),f=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let x=1,w=c.sqr(g);for(;!c.eql(w,c.ONE);)if(x++,w=c.sqr(w),x===u)throw new Error("Cannot find square root");const E=se<<BigInt(u-x-1),I=c.pow(p,E);u=x,p=c.sqr(I),g=c.mul(g,p),f=c.mul(f,I)}return f}}function uo(s){return s%ls===cs?fs:s%us===ds?co:s%hs===ao?lo(s):_s(s)}const ho=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function po(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=ho.reduce((t,n)=>(t[n]="function",t),e);return zt(s,r),s}function fo(s,e,r){if(r<ie)throw new Error("invalid exponent, negatives unsupported");if(r===ie)return s.ONE;if(r===se)return e;let t=s.ONE,n=e;for(;r>ie;)r&se&&(t=s.mul(t,n)),n=s.sqr(n),r>>=se;return t}function gs(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 xs(s,e){const r=(s.ORDER-se)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function _o(s,e){e!==void 0&&Ee(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class go{constructor(e,r={}){N(this,"ORDER");N(this,"BITS");N(this,"BYTES");N(this,"isLE");N(this,"ZERO",ie);N(this,"ONE",se);N(this,"_lengths");N(this,"_sqrt");N(this,"_mod");var o;if(e<=ie)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}=_o(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 ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ie<=e&&e<this.ORDER}is0(e){return e===ie}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}neg(e){return ue(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return ue(e*e,this.ORDER)}add(e,r){return ue(e+r,this.ORDER)}sub(e,r){return ue(e-r,this.ORDER)}mul(e,r){return ue(e*r,this.ORDER)}pow(e,r){return fo(this,e,r)}div(e,r){return ue(e*ps(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 ps(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=uo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?os(e,this.BYTES):qt(e,this.BYTES)}fromBytes(e,r=!1){V(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?is(e):xt(e);if(a&&(c=ue(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return gs(this,e)}cmov(e,r,t){return t?r:e}}function mt(s,e={}){return new go(s,e)}function ws(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 ms(s){const e=ws(s);return e+Math.ceil(e/2)}function xo(s,e,r=!1){V(s);const t=s.length,n=ws(e),i=ms(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?is(s):xt(s),a=ue(o,e-se)+se;return r?os(a,n):qt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Je=BigInt(0),De=BigInt(1);function yt(s,e){const r=e.negate();return s?r:e}function ys(s,e){const r=gs(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function bs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function jt(s,e){bs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Vt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function Ss(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,p=a===0,g=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:p,isNeg:g,isNegF:f,offsetF:l}}const Yt=new WeakMap,vs=new WeakMap;function Xt(s){return vs.get(s)||1}function Es(s){if(s!==Je)throw new Error("invalid wNAF")}class wo{constructor(e,r){N(this,"BASE");N(this,"ZERO");N(this,"Fn");N(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>Je;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=jt(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=jt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:p,isNegF:g,offsetF:f}=Ss(t,a,o);t=c,u?i=i.add(yt(g,r[f])):n=n.add(yt(p,r[l]))}return Es(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=jt(e,this.bits);for(let o=0;o<i.windows&&t!==Je;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Ss(t,o,i);if(t=a,!l){const p=r[c];n=n.add(u?p.negate():p)}}return Es(t),n}getPrecomputes(e,r,t){let n=Yt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Yt.set(r,n))),n}cached(e,r,t){const n=Xt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=Xt(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){bs(r,this.bits),vs.set(e,r),Yt.delete(e)}hasCache(e){return Xt(e)!==1}}function mo(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Je||t>Je;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function As(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return po(e),e}else return mt(s,{isLE:r})}function yo(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>Je))throw new Error(`CURVE.${c} must be positive bigint`)}const n=As(e.p,r.Fp,t),i=As(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 bo(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class Is{constructor(e,r){N(this,"oHash");N(this,"iHash");N(this,"blockLen");N(this,"outputLen");N(this,"finished",!1);N(this,"destroyed",!1);if(jr(e),V(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),ze(n)}update(e){return Ve(this),this.iHash.update(e),this}digestInto(e){Ve(this),V(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 Ts=(s,e,r)=>new Is(s,e).update(r).digest();Ts.create=(s,e)=>new Is(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Rs=(s,e)=>(s+(s>=0?e:-e)/ks)/e;function So(s,e,r){const[[t,n],[i,o]]=e,a=Rs(o*s,r),c=Rs(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const p=l<Ie,g=u<Ie;p&&(l=-l),g&&(u=-u);const f=Vt(Math.ceil(no(r)/2))+je;if(l<Ie||l>=f||u<Ie||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:p,k1:l,k2neg:g,k2:u}}function Zt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Qt(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return _t(r.lowS,"lowS"),_t(r.prehash,"prehash"),r.format!==void 0&&Zt(r.format),r}class vo extends Error{constructor(e=""){super(e)}}const Pe={Err:vo,_tlv:{encode:(s,e)=>{const{Err:r}=Pe;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=gt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?gt(n.length/2|128):"";return gt(s)+i+n+e},decode(s,e){const{Err:r}=Pe;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=Pe;if(s<Ie)throw new e("integer: negative integers are not allowed");let r=gt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Pe;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return xt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Pe,n=V(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Pe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),je=BigInt(1),ks=BigInt(2),bt=BigInt(3),Eo=BigInt(4);function Ao(s,e={}){const r=yo("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;zt(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=Cs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function p(W,m,y){const{x:R,y:P}=m.toAffine(),M=t.toBytes(R);if(_t(y,"isCompressed"),y){u();const b=!t.isOdd(P);return ke(Os(b),M)}else return ke(Uint8Array.of(4),M,t.toBytes(P))}function g(W){V(W,void 0,"Point");const{publicKey:m,publicKeyUncompressed:y}=l,R=W.length,P=W[0],M=W.subarray(1);if(R===m&&(P===2||P===3)){const b=t.fromBytes(M);if(!t.isValid(b))throw new Error("bad point: is not on curve, wrong x");const S=w(b);let A;try{A=t.sqrt(S)}catch(H){const F=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();const T=t.isOdd(A);return(P&1)===1!==T&&(A=t.neg(A)),{x:b,y:A}}else if(R===y&&P===4){const b=t.BYTES,S=t.fromBytes(M.subarray(0,b)),A=t.fromBytes(M.subarray(b,b*2));if(!E(S,A))throw new Error("bad point: is not on curve");return{x:S,y:A}}else throw new Error(`bad point: got length ${R}, expected compressed=${m} or uncompressed=${y}`)}const f=e.toBytes||p,x=e.fromBytes||g;function w(W){const m=t.sqr(W),y=t.mul(m,W);return t.add(t.add(y,t.mul(W,i.a)),i.b)}function E(W,m){const y=t.sqr(m),R=w(W);return t.eql(y,R)}if(!E(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(i.a,bt),Eo),C=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(I,C)))throw new Error("bad curve params: a or b");function k(W,m,y=!1){if(!t.isValid(m)||y&&t.is0(m))throw new Error(`bad point coordinate ${W}`);return m}function L(W){if(!(W instanceof X))throw new Error("Weierstrass Point expected")}function B(W){if(!c||!c.basises)throw new Error("no endo");return So(W,c.basises,n.ORDER)}const K=as((W,m)=>{const{X:y,Y:R,Z:P}=W;if(t.eql(P,t.ONE))return{x:y,y:R};const M=W.is0();m==null&&(m=M?t.ONE:t.inv(P));const b=t.mul(y,m),S=t.mul(R,m),A=t.mul(P,m);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(A,t.ONE))throw new Error("invZ was invalid");return{x:b,y:S}}),Q=as(W=>{if(W.is0()){if(e.allowInfinityPoint&&!t.is0(W.Y))return;throw new Error("bad point: ZERO")}const{x:m,y}=W.toAffine();if(!t.isValid(m)||!t.isValid(y))throw new Error("bad point: x or y not field elements");if(!E(m,y))throw new Error("bad point: equation left != right");if(!W.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function G(W,m,y,R,P){return y=new X(t.mul(y.X,W),y.Y,y.Z),m=yt(R,m),y=yt(P,y),m.add(y)}const D=class D{constructor(m,y,R){N(this,"X");N(this,"Y");N(this,"Z");this.X=k("x",m),this.Y=k("y",y,!0),this.Z=k("z",R),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:y,y:R}=m||{};if(!m||!t.isValid(y)||!t.isValid(R))throw new Error("invalid affine point");if(m instanceof D)throw new Error("projective point not allowed");return t.is0(y)&&t.is0(R)?D.ZERO:new D(y,R,t.ONE)}static fromBytes(m){const y=D.fromAffine(x(V(m,void 0,"point")));return y.assertValidity(),y}static fromHex(m){return D.fromBytes(pt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,y=!0){return U.createCache(this,m),y||this.multiply(bt),this}assertValidity(){Q(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){L(m);const{X:y,Y:R,Z:P}=this,{X:M,Y:b,Z:S}=m,A=t.eql(t.mul(y,S),t.mul(M,P)),T=t.eql(t.mul(R,S),t.mul(b,P));return A&&T}negate(){return new D(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:y}=i,R=t.mul(y,bt),{X:P,Y:M,Z:b}=this;let S=t.ZERO,A=t.ZERO,T=t.ZERO,O=t.mul(P,P),H=t.mul(M,M),F=t.mul(b,b),$=t.mul(P,M);return $=t.add($,$),T=t.mul(P,b),T=t.add(T,T),S=t.mul(m,T),A=t.mul(R,F),A=t.add(S,A),S=t.sub(H,A),A=t.add(H,A),A=t.mul(S,A),S=t.mul($,S),T=t.mul(R,T),F=t.mul(m,F),$=t.sub(O,F),$=t.mul(m,$),$=t.add($,T),T=t.add(O,O),O=t.add(T,O),O=t.add(O,F),O=t.mul(O,$),A=t.add(A,O),F=t.mul(M,b),F=t.add(F,F),O=t.mul(F,$),S=t.sub(S,O),T=t.mul(F,H),T=t.add(T,T),T=t.add(T,T),new D(S,A,T)}add(m){L(m);const{X:y,Y:R,Z:P}=this,{X:M,Y:b,Z:S}=m;let A=t.ZERO,T=t.ZERO,O=t.ZERO;const H=i.a,F=t.mul(i.b,bt);let $=t.mul(y,M),q=t.mul(R,b),Y=t.mul(P,S),ce=t.add(y,R),j=t.add(M,b);ce=t.mul(ce,j),j=t.add($,q),ce=t.sub(ce,j),j=t.add(y,P);let ne=t.add(M,S);return j=t.mul(j,ne),ne=t.add($,Y),j=t.sub(j,ne),ne=t.add(R,P),A=t.add(b,S),ne=t.mul(ne,A),A=t.add(q,Y),ne=t.sub(ne,A),O=t.mul(H,j),A=t.mul(F,Y),O=t.add(A,O),A=t.sub(q,O),O=t.add(q,O),T=t.mul(A,O),q=t.add($,$),q=t.add(q,$),Y=t.mul(H,Y),j=t.mul(F,j),q=t.add(q,Y),Y=t.sub($,Y),Y=t.mul(H,Y),j=t.add(j,Y),$=t.mul(q,j),T=t.add(T,$),$=t.mul(ne,j),A=t.mul(ce,A),A=t.sub(A,$),$=t.mul(ce,q),O=t.mul(ne,O),O=t.add(O,$),new D(A,T,O)}subtract(m){return this.add(m.negate())}is0(){return this.equals(D.ZERO)}multiply(m){const{endo:y}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let R,P;const M=b=>U.cached(this,b,S=>ys(D,S));if(y){const{k1neg:b,k1:S,k2neg:A,k2:T}=B(m),{p:O,f:H}=M(S),{p:F,f:$}=M(T);P=H.add($),R=G(y.beta,O,F,b,A)}else{const{p:b,f:S}=M(m);R=b,P=S}return ys(D,[R,P])[0]}multiplyUnsafe(m){const{endo:y}=e,R=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ie||R.is0())return D.ZERO;if(m===je)return R;if(U.hasCache(this))return this.multiply(m);if(y){const{k1neg:P,k1:M,k2neg:b,k2:S}=B(m),{p1:A,p2:T}=mo(D,R,M,S);return G(y.beta,A,T,P,b)}else return U.unsafe(R,m)}toAffine(m){return K(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===je?!0:m?m(D,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===je?this:m?m(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return _t(m,"isCompressed"),this.assertValidity(),f(D,this,m)}toHex(m=!0){return et(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};N(D,"BASE",new D(i.Gx,i.Gy,t.ONE)),N(D,"ZERO",new D(t.ZERO,t.ONE,t.ZERO)),N(D,"Fp",t),N(D,"Fn",n);let X=D;const re=n.BITS,U=new wo(X,e.endo?Math.ceil(re/2):re);return X.BASE.precompute(8),X}function Os(s){return Uint8Array.of(s?2:3)}function Cs(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Io(s,e={}){const{Fn:r}=s,t=e.randomBytes||ts,n=Object.assign(Cs(s.Fp,r),{seed:ms(r.ORDER)});function i(f){try{const x=r.fromBytes(f);return r.isValidNot0(x)}catch{return!1}}function o(f,x){const{publicKey:w,publicKeyUncompressed:E}=n;try{const I=f.length;return x===!0&&I!==w||x===!1&&I!==E?!1:!!s.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return xo(V(f,n.seed,"seed"),r.ORDER)}function c(f,x=!0){return s.BASE.multiply(r.fromBytes(f)).toBytes(x)}function l(f){const{secretKey:x,publicKey:w,publicKeyUncompressed:E}=n;if(!Ut(f)||"_lengths"in r&&r._lengths||x===w)return;const I=V(f,void 0,"key").length;return I===w||I===E}function u(f,x,w=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const E=r.fromBytes(f);return s.fromBytes(x).multiply(E).toBytes(w)}const p={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=bo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:g,Point:s,utils:p,lengths:n})}function To(s,e,r={}){jr(e),zt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||ts,n=r.hmac||((m,y)=>Ts(e,m,y)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:f}=Io(s,r),x={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},w=a*ks<i.ORDER;function E(m){const y=a>>je;return m>y}function I(m,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function C(){if(w)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function k(m,y){Zt(y);const R=f.signature,P=y==="compact"?R:y==="recovered"?R+1:void 0;return V(m,P)}class L{constructor(y,R,P){N(this,"r");N(this,"s");N(this,"recovery");if(this.r=I("r",y),this.s=I("s",R),P!=null){if(C(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(y,R=x.format){k(y,R);let P;if(R==="der"){const{r:A,s:T}=Pe.toSig(V(y));return new L(A,T)}R==="recovered"&&(P=y[0],R="compact",y=y.subarray(1));const M=f.signature/2,b=y.subarray(0,M),S=y.subarray(M,M*2);return new L(o.fromBytes(b),o.fromBytes(S),P)}static fromHex(y,R){return this.fromBytes(pt(y),R)}assertRecovery(){const{recovery:y}=this;if(y==null)throw new Error("invalid recovery id: must be present");return y}addRecoveryBit(y){return new L(this.r,this.s,y)}recoverPublicKey(y){const{r:R,s:P}=this,M=this.assertRecovery(),b=M===2||M===3?R+a:R;if(!i.isValid(b))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const S=i.toBytes(b),A=s.fromBytes(ke(Os((M&1)===0),S)),T=o.inv(b),O=K(V(y,void 0,"msgHash")),H=o.create(-O*T),F=o.create(P*T),$=s.BASE.multiplyUnsafe(H).add(A.multiplyUnsafe(F));if($.is0())throw new Error("invalid recovery: point at infinify");return $.assertValidity(),$}hasHighS(){return E(this.s)}toBytes(y=x.format){if(Zt(y),y==="der")return pt(Pe.hexFromSig(this));const{r:R,s:P}=this,M=o.toBytes(R),b=o.toBytes(P);return y==="recovered"?(C(),ke(Uint8Array.of(this.assertRecovery()),M,b)):ke(M,b)}toHex(y){return et(this.toBytes(y))}}const B=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const R=xt(y),P=y.length*8-c;return P>0?R>>BigInt(P):R},K=r.bits2int_modN||function(y){return o.create(B(y))},Q=Vt(c);function G(m){return so("num < 2^"+c,m,Ie,Q),o.toBytes(m)}function X(m,y){return V(m,void 0,"message"),y?V(e(m),void 0,"prehashed message"):m}function re(m,y,R){const{lowS:P,prehash:M,extraEntropy:b}=Qt(R,x);m=X(m,M);const S=K(m),A=o.fromBytes(y);if(!o.isValidNot0(A))throw new Error("invalid private key");const T=[G(A),G(S)];if(b!=null&&b!==!1){const $=b===!0?t(f.secretKey):b;T.push(V($,void 0,"extraEntropy"))}const O=ke(...T),H=S;function F($){const q=B($);if(!o.isValidNot0(q))return;const Y=o.inv(q),ce=s.BASE.multiply(q).toAffine(),j=o.create(ce.x);if(j===Ie)return;const ne=o.create(Y*o.create(H+j*A));if(ne===Ie)return;let rn=(ce.x===j?0:2)|Number(ce.y&je),sn=ne;return P&&E(ne)&&(sn=o.neg(ne),rn^=1),new L(j,sn,w?void 0:rn)}return{seed:O,k2sig:F}}function U(m,y,R={}){const{seed:P,k2sig:M}=re(m,y,R);return io(e.outputLen,o.BYTES,n)(P,M).toBytes(R.format)}function D(m,y,R,P={}){const{lowS:M,prehash:b,format:S}=Qt(P,x);if(R=V(R,void 0,"publicKey"),y=X(y,b),!Ut(m)){const A=m instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+A)}k(m,S);try{const A=L.fromBytes(m,S),T=s.fromBytes(R);if(M&&A.hasHighS())return!1;const{r:O,s:H}=A,F=K(y),$=o.inv(H),q=o.create(F*$),Y=o.create(O*$),ce=s.BASE.multiplyUnsafe(q).add(T.multiplyUnsafe(Y));return ce.is0()?!1:o.create(ce.x)===O}catch{return!1}}function W(m,y,R={}){const{prehash:P}=Qt(R,x);return y=X(y,P),L.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:p,utils:g,lengths:f,Point:s,sign:U,verify:D,recoverPublicKey:W,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const er={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Ro={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Ps=BigInt(2);function ko(s){const e=er.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,p=le(u,r,e)*u%e,g=le(p,r,e)*u%e,f=le(g,Ps,e)*l%e,x=le(f,n,e)*f%e,w=le(x,i,e)*x%e,E=le(w,a,e)*w%e,I=le(E,c,e)*E%e,C=le(I,a,e)*w%e,k=le(C,r,e)*u%e,L=le(k,o,e)*x%e,B=le(L,t,e)*l%e,K=le(B,Ps,e);if(!tr.eql(tr.sqr(K),s))throw new Error("Cannot find square root");return K}const tr=mt(er.p,{sqrt:ko}),Oo=To(Ao(er,{Fp:tr,endo:Ro}),eo),Co=BigInt(0),tt=BigInt(1),Po=BigInt(2),No=BigInt(7),Lo=BigInt(256),Do=BigInt(113),Ns=[],Ls=[],Ds=[];for(let s=0,e=tt,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],Ns.push(2*(5*t+r)),Ls.push((s+1)*(s+2)/2%64);let n=Co;for(let i=0;i<7;i++)e=(e<<tt^(e>>No)*Do)%Lo,e&Po&&(n^=tt<<(tt<<BigInt(i))-tt);Ds.push(n)}const $s=Vi(Ds,!0),$o=$s[0],Mo=$s[1],Ms=(s,e,r)=>r>32?ji(s,e,r):zi(s,e,r),Bs=(s,e,r)=>r>32?Yi(s,e,r):Ji(s,e,r);function Bo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],p=Ms(l,u,1)^r[a],g=Bs(l,u,1)^r[a+1];for(let f=0;f<50;f+=10)s[o+f]^=p,s[o+f+1]^=g}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=Ls[o],c=Ms(n,i,a),l=Bs(n,i,a),u=Ns[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=$o[t],s[1]^=Mo[t]}ze(r)}class rr{constructor(e,r,t,n=!1,i=24){N(this,"state");N(this,"pos",0);N(this,"posOut",0);N(this,"finished",!1);N(this,"state32");N(this,"destroyed",!1);N(this,"blockLen");N(this,"suffix");N(this,"outputLen");N(this,"enableXOF",!1);N(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,Ee(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=$i(this.state)}clone(){return this._cloneInto()}keccak(){Xr(this.state32),Bo(this.state32,this.rounds),Xr(this.state32),this.posOut=0,this.pos=0}update(e){Ve(this),V(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ve(this,!1),V(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 Ee(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Yr(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,ze(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new rr(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 Ws=((s,e,r,t={})=>es(()=>new rr(e,s,r),t))(1,136,32),Wo=60;class Fo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Ni(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Wo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Ei(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Di(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=Ws(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Uo(a),l=c.slice(0,32),u=c.slice(32,64),p=c[64],g=p>=27?p-27:p,w=new Oo.Signature(Fs(l),Fs(u)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),E=Ws(w);return"0x"+et(E.slice(12))}}function Uo(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 Fs(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Ho=3e4,Go=1e3;class Ko{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,Go*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Ho);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const qo=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class $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(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await $e.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=$e.generateRandom16Hex(),l=$e.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",p=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(p,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const f=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),L(),t(new Error("Authentication timeout"))},5*60*1e3),x=10,w=30;let E=0,I=null;const C=()=>{clearInterval(k),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+w+"초간 대기합니다"),I=setTimeout(()=>{L(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},w*1e3)},k=setInterval(()=>{E++;try{g.closed&&(E<=x?C():(L(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),L=()=>{clearTimeout(f),clearInterval(k),I&&clearTimeout(I),window.removeEventListener("message",B)},B=K=>{if(K.origin!==e.expectedOrigin)return;if(!qo.has(K.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",K.origin),L(),t(new Error("Unauthorized OAuth origin"));return}L();const Q=typeof K.data.status=="string",G=Q?K.data.data??{}:K.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Q?"wrapped":"flat",status:Q?K.data.status:"(flat)"});const X=(G==null?void 0:G.state)??K.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Q&&K.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",G==null?void 0:G.error),t(new Error((G==null?void 0:G.error)||"Authentication failed"));return}if(!Q&&(G!=null&&G.error)){d.error("[CROSSx] OAuth 실패:",G.error),t(new Error(G.error||"Authentication failed"));return}const re=G==null?void 0:G.idToken,U=G==null?void 0:G.accessToken,D=U??re,W=(G==null?void 0:G.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!re,hasEmail:!!W}),!D){d.error("[CROSSx] 토큰을 찾을 수 없음:",K.data),t(new Error("Token not found in response"));return}const m={token:D,email:W},y=R=>{$e.verifyIdTokenNonce(R,l).then(()=>r(m)).catch(P=>{d.error("[CROSSx] nonce 검증 실패:",P),t(P instanceof Error?P:new Error("nonce verification failed"))})};U?U.split(".").length===3?y(U):re?y(re):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(m)):re?y(re):t(new Error("Token not found in response"))};window.addEventListener("message",B)})}}const rt="crossx_wallet_data",Ye="crossx_mock_pin_hash";class Vo{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(rt)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(rt);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(rt,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Ye,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new _(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(rt);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ye);return r&&r!==e?!1:(r||await this.storage.set(Ye,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new _(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ye);if(n&&t&&n!==t)throw new _(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ye,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new _(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(rt,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ye,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Me{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(vr))return e;const r=!e||this.tokenStore.isExpiringSoon(vr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,p;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const f=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(f&&typeof f.code=="number"){if(f.code<0||f.code>=400){const x=f.message||f.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:f.code,message:x,url:o,method:e});const w=Me.mapGatewayError(f.code,f.data);if(w===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(w===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new _(h.USER_NOT_FOUND,Me.getGatewayErrorMessage(f.code,x));const E=w===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:w,I=E===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Me.getGatewayErrorMessage(f.code,x),C=f.data;let k;throw w===h.PIN_LOCKED?k=Me.extractLockDetails(C):w===h.ADDRESS_LIMIT_EXCEEDED?k={limit:ot,raw:C}:k=C??void 0,new _(E,I,k)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:f.code,url:o,method:e}),f.data??f}return f}catch(g){if(g instanceof _)throw g;const f=((l=g.response)==null?void 0:l.status)??g.status;if((f===401||f===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${f} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=g.response)!=null&&u.data){const x=g.response.data,w=x.message||x.data||"API 요청에 실패했습니다",E=x.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:w,url:o,method:e,status:(p=g.response)==null?void 0:p.status}),new _(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${w}`)}throw g}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index,name:t.name}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new _(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){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new _(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-10028:return Me.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return`Transaction broadcast failed (${r}). Please try again.`;case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10036:return`Account limit reached. Maximum ${ot} accounts allowed.`;case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class zo{constructor(e,r,t){this.inner=e,this.getBridge=r,this.isAuthenticatedViaRNBridge=t,e.checkWallet&&(this.checkWallet=()=>e.checkWallet()),e.prepare&&(this.prepare=(n,i)=>e.prepare(n,i)),e.migrateWallet&&(this.migrateWallet=(n,i)=>e.migrateWallet(n,i)),e.verifyPin&&(this.verifyPin=n=>e.verifyPin(n)),e.getShareC&&(this.getShareC=()=>e.getShareC()),e.verifyRecoveryPin&&(this.verifyRecoveryPin=(n,i)=>e.verifyRecoveryPin(n,i))}shouldUseBridge(){if(!this.isAuthenticatedViaRNBridge())return null;const e=this.getBridge();return e!=null&&e.isInstalled?e:null}async signMessage(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signMessage){const c=await a.signMessage({chainId:r,message:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}return this.inner.signMessage(e,r,t,n,i,o)}async signTypedData(e,r,t,n,i,o){const a=this.shouldUseBridge();if(a!=null&&a.signTypedData){const c=await a.signTypedData({chainId:r,typedData:t,from:o,index:n});return{chainId:r,signature:c.signature,format:"hex"}}if(!this.inner.signTypedData)throw new Error("signTypedData not supported by inner wallet provider");return this.inner.signTypedData(e,r,t,n,i,o)}async signTransaction(e,r,t,n,i){const o=this.shouldUseBridge();if(o!=null&&o.signTransaction){const a=await o.signTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from,index:n});return{chainId:r,signature:a.signedTx,format:"hex"}}return this.inner.signTransaction(e,r,t,n,i)}async sendTransaction(e,r,t,n){const i=this.shouldUseBridge();if(i!=null&&i.sendTransaction)return{txHash:(await i.sendTransaction({chainId:r,tx:this.toBridgeTx(t),from:t.from})).txHash};if(!this.inner.sendTransaction)throw new Error("sendTransaction not supported by inner wallet provider");return this.inner.sendTransaction(e,r,t,n)}toBridgeTx(e){return{to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce}}getOrCreateWallet(e){return this.inner.getOrCreateWallet(e)}getAddresses(e){return this.inner.getAddresses(e)}getAddress(e,r){return this.inner.getAddress(e,r)}setOnUnauthorized(e){var r,t;(t=(r=this.inner).setOnUnauthorized)==null||t.call(r,e)}setTokenRefresher(e){var r,t;(t=(r=this.inner).setTokenRefresher)==null||t.call(r,e)}}class st{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=st.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?En:vn;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 _(st.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=st.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new _(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(nt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Us="__crossx-confirm-style",te="__crossx-confirm-overlay",Jo={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function Hs(s,e){const r=Jo[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const jo=`
7
8
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
8
9
 
9
- #${ee} {
10
+ #${te} {
10
11
  position: fixed;
11
12
  inset: 0;
12
13
  z-index: 2147483647;
@@ -1373,6 +1374,18 @@ button.__crossx-connect-other-block:active {
1373
1374
  line-height: 1.3;
1374
1375
  color: var(--cx-subtitle);
1375
1376
  }
1377
+ .__crossx-wallet-add-error {
1378
+ margin: 8px 0 0;
1379
+ padding: 8px 10px;
1380
+ font-size: 13px;
1381
+ line-height: 1.45;
1382
+ color: var(--cx-error);
1383
+ background: color-mix(in srgb, var(--cx-error) 10%, transparent);
1384
+ border: 1px solid color-mix(in srgb, var(--cx-error) 35%, transparent);
1385
+ border-radius: 8px;
1386
+ word-break: break-word;
1387
+ }
1388
+ .__crossx-wallet-add-error[hidden] { display: none; }
1376
1389
 
1377
1390
  /* ── Safe area fill (mobile only, created by JS in mountOverlay) ── */
1378
1391
  .__crossx-safe-area-fill {
@@ -1380,7 +1393,7 @@ button.__crossx-connect-other-block:active {
1380
1393
  }
1381
1394
  /* ── Mobile bottom sheet ───────────────────────────────────── */
1382
1395
  @media (max-width: 480px) {
1383
- #${ee} { align-items: flex-end; }
1396
+ #${te} { align-items: flex-end; }
1384
1397
  .__crossx-safe-area-fill {
1385
1398
  display: block;
1386
1399
  position: fixed;
@@ -1590,7 +1603,7 @@ button.__crossx-connect-other-block:active {
1590
1603
 
1591
1604
  /* ── Landscape for signing/transaction modals ──────────── */
1592
1605
  @media (orientation: landscape) and (max-height: 500px) {
1593
- #${ee} { align-items: center !important; overflow: hidden; }
1606
+ #${te} { align-items: center !important; overflow: hidden; }
1594
1607
  .__crossx-card--send-tx,
1595
1608
  .__crossx-card--sign-tx,
1596
1609
  .__crossx-card--sign-msg,
@@ -2085,30 +2098,53 @@ button.__crossx-connect-other-block:active {
2085
2098
  color: var(--cx-title);
2086
2099
  margin: 0;
2087
2100
  }
2088
- `;function he(){let r=document.getElementById(Wr);r||(r=document.createElement("style"),r.id=Wr,document.head.appendChild(r)),r.textContent=Vo}function zo(){const r=`#${ee}`,e=t=>{var n,i;(i=(n=t.target)==null?void 0:n.closest)!=null&&i.call(n,r)&&t.stopImmediatePropagation()},s=t=>{var n,i;(i=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&i.call(n,r)&&t.stopImmediatePropagation()};return document.addEventListener("focusin",e,!0),document.addEventListener("focusout",s,!0),()=>{document.removeEventListener("focusin",e,!0),document.removeEventListener("focusout",s,!0)}}function pe(r){const e=r.querySelector(".__crossx-card");if(e){const o=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(o){const a=o[1].trim();r.style.setProperty("--cx-bg",a);const c=document.createElement("div");c.className="__crossx-safe-area-fill",c.style.background=a,r.appendChild(c)}}const s=i=>i.stopPropagation();for(const i of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(i,s);r.setAttribute("data-vaul-no-drag","");for(const i of["touchstart","touchend"])r.addEventListener(i,s);r.addEventListener("touchmove",i=>{i.stopPropagation();let o=i.target;for(;o&&o!==r;){const a=window.getComputedStyle(o);if((a.overflowY==="auto"||a.overflowY==="scroll")&&o.scrollHeight>o.clientHeight)return;o=o.parentElement}i.preventDefault()},{passive:!1});const t=zo(),n=r.remove.bind(r);r.remove=()=>{t(),n()},document.body.appendChild(r)}const Jo=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Xe(){if(Jo()){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 r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}}function fe(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function Ur(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=ss(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Hr={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Gr(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Hr[e]?Hr[e]:r}function ss(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,o=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function rs(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function Yo(r){try{return BigInt(r).toLocaleString()}catch{return r}}function jo(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=18}=r;if(!e)return null;try{const a=BigInt(e),c=Yo(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${ss(l,o)} ${i}`,maxFeeGwei:rs(t),maxPriorityFeeGwei:n?rs(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${ss(l,o)} ${i}`,gasPriceGwei:rs(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Kr(r){const e=jo(r);if(!e)return J("Estimated fee","<span>—</span>");let s=J("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=J("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=J("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=J("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=J("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}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">
2101
+
2102
+ /* ── Amount tooltip ──────────────────────────────────────────────── */
2103
+ .__crossx-amount-tip {
2104
+ cursor: default;
2105
+ }
2106
+ .__crossx-tip-overlay {
2107
+ position: fixed;
2108
+ background: #111827;
2109
+ color: #e2e8f0;
2110
+ border-radius: 8px;
2111
+ padding: 6px 10px;
2112
+ font-size: 12px;
2113
+ font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
2114
+ line-height: 1.4;
2115
+ white-space: nowrap;
2116
+ pointer-events: none;
2117
+ z-index: 1;
2118
+ box-shadow: 0 4px 12px rgba(0,0,0,0.3);
2119
+ display: none;
2120
+ }
2121
+ .__crossx-tip-overlay.--visible {
2122
+ display: block;
2123
+ }
2124
+ `;function he(){let s=document.getElementById(Us);s||(s=document.createElement("style"),s.id=Us,document.head.appendChild(s)),s.textContent=jo}function Yo(){const s=`#${te}`,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 pe(s){const e=s.querySelector(".__crossx-card");if(e){const o=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(o){const a=o[1].trim();s.style.setProperty("--cx-bg",a);const c=document.createElement("div");c.className="__crossx-safe-area-fill",c.style.background=a,s.appendChild(c)}}const r=i=>i.stopPropagation();for(const i of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(i,r);s.setAttribute("data-vaul-no-drag","");for(const i of["touchstart","touchend"])s.addEventListener(i,r);s.addEventListener("touchmove",i=>{i.stopPropagation();let o=i.target;for(;o&&o!==s;){const a=window.getComputedStyle(o);if((a.overflowY==="auto"||a.overflowY==="scroll")&&o.scrollHeight>o.clientHeight)return;o=o.parentElement}i.preventDefault()},{passive:!1});const t=Yo(),n=s.remove.bind(s);s.remove=()=>{t(),n()},document.body.appendChild(s)}function Xo(s){const e=Array.from(s.querySelectorAll(".__crossx-amount-tip"));if(!e.length)return;const r=document.createElement("div");r.className="__crossx-tip-overlay",s.appendChild(r);let t=null;const n=o=>{const a=o.dataset.full;if(!a)return;r.textContent=a,r.classList.add("--visible");const c=o.getBoundingClientRect(),l=r.offsetWidth,u=r.offsetHeight;let p=c.right-l,g=c.top-u-6;p<8&&(p=8),g<8&&(g=c.bottom+6),r.style.left=`${p}px`,r.style.top=`${g}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 Zo=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Xe(){if(Zo()){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 fe(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function Gs(s,e="CROSS",r=18,t=6){if(!s||s==="0x"||s==="0x0")return null;try{const n=BigInt(s);if(n===0n)return null;const i=ir(n,r,t);if(i==="0")return null;const o=sr(n,r);return nr(`${i} ${e}`,`${o} ${e}`)}catch{return null}}const Ks={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function qs(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&Ks[e]?Ks[e]:s}function sr(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 nr(s,e){return s===e?v(s):`<span class="__crossx-amount-tip" data-full="${v(e)}">${v(s)}</span>`}function ir(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 or(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 Qo(s){try{return BigInt(s).toLocaleString()}catch{return s}}function ea(s,e){const{gasLimit:r,gasPrice:t,maxFeePerGas:n,maxPriorityFeePerGas:i,nativeSymbol:o="ETH",nativeDecimals:a=18}=s;if(!r)return null;try{const c=BigInt(r),l=Qo(r);if(n){const u=c*BigInt(n);return{isDynamic:!0,estTxFee:nr(`${ir(u,a,e)} ${o}`,`${sr(u,a)} ${o}`),maxFeeGwei:or(n),maxPriorityFeeGwei:i?or(i):void 0,gasLimitFormatted:l}}if(t){const u=c*BigInt(t);return{isDynamic:!1,estTxFee:nr(`${ir(u,a,e)} ${o}`,`${sr(u,a)} ${o}`),gasPriceGwei:or(t),gasLimitFormatted:l}}return{isDynamic:!1,estTxFee:`${c.toLocaleString()} gas`,gasLimitFormatted:l}}catch{return null}}function Vs(s,e,r){const t=ea(s,e);if(!t)return J((r==null?void 0:r.label_estimated_fee)??"Estimated fee","<span>—</span>");let n=J((r==null?void 0:r.label_est_tx_fee)??"Est. Tx Fee",`<span>${t.estTxFee}</span>`);return t.isDynamic?(t.maxPriorityFeeGwei!==void 0&&(n+=J((r==null?void 0:r.label_max_priority_fee)??"Max Priority Fee",`<span>${t.maxPriorityFeeGwei} Gwei</span>`)),t.maxFeeGwei!==void 0&&(n+=J((r==null?void 0:r.label_max_gas_fee)??"Max Gas Fee",`<span>${t.maxFeeGwei} Gwei</span>`))):t.gasPriceGwei!==void 0&&(n+=J((r==null?void 0:r.label_gas_price)??"Gas Price",`<span>${t.gasPriceGwei} Gwei</span>`)),t.gasLimitFormatted&&(n+=J((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">
2089
2125
  <rect x="9" y="9" width="13" height="13" rx="2"/>
2090
2126
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
2091
2127
  </svg>`,oe=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
2092
2128
  <line x1="18" y1="6" x2="6" y2="18"/>
2093
2129
  <line x1="6" y1="6" x2="18" y2="18"/>
2094
- </svg>`,Xo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2130
+ </svg>`,ta=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2095
2131
  <circle cx="20" cy="20" r="20" fill="#00D5AA"/>
2096
2132
  <path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/>
2097
- </svg>`,Zo='<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>',Qo='<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>',ea='<svg width="16" height="16" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="20" cy="20" r="20" fill="#00D5AA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/></svg>',ta={[We.MetaMask]:Zo,[We.Binance]:Qo,[We.CROSSx]:ea},qr='<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"/>',ns=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${qr}</svg>`,sa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2133
+ </svg>`,ra='<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>',sa='<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>',na='<svg width="16" height="16" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="20" cy="20" r="20" fill="#00D5AA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/></svg>',ia={[We.MetaMask]:ra,[We.Binance]:sa,[We.CROSSx]:na},zs='<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"/>',ar=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${zs}</svg>`,oa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2098
2134
  <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)"/>
2099
- </svg>`,ra=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2135
+ </svg>`,aa=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2100
2136
  <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
2101
2137
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
2102
2138
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
2103
- </svg>`;function ae(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function J(r,e){return`
2139
+ </svg>`;function ae(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function J(s,e){return`
2104
2140
  <div class="__crossx-row">
2105
- <span class="__crossx-row-label">${r}</span>
2141
+ <span class="__crossx-row-label">${s}</span>
2106
2142
  <div class="__crossx-row-value">${e}</div>
2107
- </div>`}function na(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=bt(r.dappName),o=r.to?`<span class="__crossx-addr-text">${fe(r.to)}</span>
2108
- <button class="__crossx-copy-btn" data-copy="${N(r.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",a=Kr(r),c=Ur(r.value,t,n),l=c?J("Value",`<span>${c}</span>`):"",u=r.data??"0x",p=document.createElement("div");return p.id=ee,p.innerHTML=`
2109
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2143
+ </div>`}function ca(s,e,r,t){const n=e,i=s.nativeSymbol??"ETH",o=s.nativeDecimals??18,a=St(s.dappName),c=s.to?`<span class="__crossx-addr-text">${fe(s.to)}</span>
2144
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=Vs(s,r,t),u=Gs(s.value,i,o,r),p=u?J((t==null?void 0:t.label_value)??"Value",`<span>${u}</span>`):"",g=s.data??"0x",f=document.createElement("div");return f.id=te,f.innerHTML=`
2145
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2110
2146
  <div class="__crossx-header">
2111
- <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
2147
+ <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.sign_transaction_title)??"Signature Request")}</p>
2112
2148
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2113
2149
  </div>
2114
2150
  <hr class="__crossx-divider">
@@ -2116,115 +2152,115 @@ button.__crossx-connect-other-block:active {
2116
2152
  <div class="__crossx-body-cols">
2117
2153
  <div class="__crossx-col-left">
2118
2154
  <p class="__crossx-sig-subtitle">
2119
- <span class="__crossx-sig-origin">${N(i)} </span>is requesting a Signature
2155
+ <span class="__crossx-sig-origin">${v(a)}</span>${v((t==null?void 0:t.signature_requesting)??" is requesting a Signature")}
2120
2156
  </p>
2121
2157
  <div class="__crossx-addr-pill">
2122
- ${ns}
2123
- <span class="__crossx-addr-pill-text">${fe(r.from)}</span>
2158
+ ${ar}
2159
+ <span class="__crossx-addr-pill-text">${fe(s.from)}</span>
2124
2160
  </div>
2125
- <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
2161
+ <p class="__crossx-warning">${v((t==null?void 0:t.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2126
2162
  </div>
2127
2163
  <hr class="__crossx-divider __crossx-divider--cols">
2128
2164
  <div class="__crossx-col-right-sign">
2129
2165
  <div class="__crossx-rows">
2130
- ${J("To",o)}
2131
- ${J("Network",`<span>${Gr(r.chainId)}</span>`)}
2166
+ ${J((t==null?void 0:t.label_to)??"To",c)}
2167
+ ${J((t==null?void 0:t.label_network)??"Network",`<span>${qs(s.chainId)}</span>`)}
2168
+ ${p}
2132
2169
  ${l}
2133
- ${a}
2134
2170
  </div>
2135
- <pre class="__crossx-raw-tx">${N(u)}</pre>
2171
+ <pre class="__crossx-raw-tx">${v(g)}</pre>
2136
2172
  </div>
2137
2173
  </div>
2138
2174
  <div class="__crossx-btn-row">
2139
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
2140
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">Sign</button>
2175
+ <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${v((t==null?void 0:t.cancel)??"Cancel")}</button>
2176
+ <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${v((t==null?void 0:t.signature_sign_button)??"Sign")}</button>
2141
2177
  </div>
2142
2178
  </div>
2143
2179
  </div>
2144
- `,p}function ia(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=bt(r.dappName),o=r.to?`<span class="__crossx-addr-text">${fe(r.to)}</span>
2145
- <button class="__crossx-copy-btn" data-copy="${N(r.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",a=Kr(r),l=Ur(r.value,t,n)??"—",u=document.createElement("div");return u.id=ee,u.innerHTML=`
2146
- <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2180
+ `,f}function la(s,e,r,t){const n=e,i=s.nativeSymbol??"ETH",o=s.nativeDecimals??18,a=St(s.dappName),c=s.to?`<span class="__crossx-addr-text">${fe(s.to)}</span>
2181
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",l=Vs(s,r,t),p=Gs(s.value,i,o,r)??"—",g=document.createElement("div");return g.id=te,g.innerHTML=`
2182
+ <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(n)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2147
2183
  <div class="__crossx-header">
2148
- <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
2184
+ <p class="__crossx-title" id="__crossx-ttl">${v((t==null?void 0:t.send_transaction_title)??"Approve transaction")}</p>
2149
2185
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2150
2186
  </div>
2151
2187
  <hr class="__crossx-divider">
2152
2188
  <div class="__crossx-body">
2153
2189
  <p class="__crossx-tx-subtitle">
2154
- <span class="__crossx-sig-origin">${N(i)}</span> wants your permission to approve the following transaction.
2190
+ <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.")}
2155
2191
  </p>
2156
2192
  <div class="__crossx-body-cols">
2157
2193
  <div class="__crossx-rows">
2158
- ${J("To",o)}
2159
- ${J("Network",`<span>${Gr(r.chainId)}</span>`)}
2160
- ${a}
2194
+ ${J((t==null?void 0:t.label_to)??"To",c)}
2195
+ ${J((t==null?void 0:t.label_network)??"Network",`<span>${qs(s.chainId)}</span>`)}
2196
+ ${l}
2161
2197
  </div>
2162
2198
  <div class="__crossx-pill">
2163
- <span class="__crossx-pill-from">${fe(r.from)}</span>
2164
- <span class="__crossx-pill-amount">${l}</span>
2199
+ <span class="__crossx-pill-from">${fe(s.from)}</span>
2200
+ <span class="__crossx-pill-amount">${p}</span>
2165
2201
  </div>
2166
2202
  </div>
2167
- <button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
2203
+ <button class="__crossx-approve-btn" id="__crossx-confirm-btn">${v((t==null?void 0:t.send_tx_approve_button)??"Approve")}</button>
2168
2204
  </div>
2169
2205
  </div>
2170
- `,u}function bt(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function N(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function oa(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function aa(r){if(typeof r=="string")return N(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return N(JSON.stringify(r))}catch{return String(r)}}function ca(r){return r.includes(":")?r.split(":")[1]??r:r}function la(r){return`https://www.crossscan.io/address/${r}?tab=txs`}function da(r,e){return`https://explorer.crosstoken.io/${ca(r)}/tx/${e}`}function Vr(r,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${N(e)}" target="_blank" rel="noopener noreferrer">${N(r)}</a>`}function St(r){return Vr(fe(r),la(r))}function zr(r,e){return Vr(fe(e),da(r,e))}function ua(r,e){const s=J("From",`${St(r.from)}
2171
- <button class="__crossx-copy-btn" data-copy="${N(r.from)}" title="Copy address">${Te}</button>`),t=r.to?J("To",`${St(r.to)}
2172
- <button class="__crossx-copy-btn" data-copy="${N(r.to)}" title="Copy address">${Te}</button>`):"",n=r.amount?J("Transfer",`<span>${N(r.amount)}</span>`):"",i=r.fees?J("Tx Fee",`<span>${N(r.fees)}</span>`):"",o=r.txHash?J("Tx Hash",`${zr(r.chainId,r.txHash)}
2173
- <button class="__crossx-copy-btn" data-copy="${N(r.txHash)}" title="Copy hash">${Te}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
2174
- <span class="__crossx-total-label">Total<br>(including fees)</span>
2175
- <span class="__crossx-total-amount">${N(r.total)}</span>
2176
- </div>`:"",c=document.createElement("div");return c.id=ee,c.innerHTML=`
2206
+ `,g}function St(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function v(s){return s.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function da(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function ua(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 ha(s){return s.includes(":")?s.split(":")[1]??s:s}function pa(s){return`https://www.crossscan.io/address/${s}?tab=txs`}function fa(s,e){return`https://explorer.crosstoken.io/${ha(s)}/tx/${e}`}function Js(s,e){return`<a class="__crossx-addr-text __crossx-row-link" href="${v(e)}" target="_blank" rel="noopener noreferrer">${v(s)}</a>`}function vt(s){return Js(fe(s),pa(s))}function js(s,e){return Js(fe(e),fa(s,e))}function _a(s,e,r){const t=J((r==null?void 0:r.label_from)??"From",`${vt(s.from)}
2207
+ <button class="__crossx-copy-btn" data-copy="${v(s.from)}" title="Copy address">${Te}</button>`),n=s.to?J((r==null?void 0:r.label_to)??"To",`${vt(s.to)}
2208
+ <button class="__crossx-copy-btn" data-copy="${v(s.to)}" title="Copy address">${Te}</button>`):"",i=s.amount?J((r==null?void 0:r.label_transfer)??"Transfer",`<span>${v(s.amount)}</span>`):"",o=s.fees?J((r==null?void 0:r.label_tx_fee)??"Tx Fee",`<span>${v(s.fees)}</span>`):"",a=s.txHash?J((r==null?void 0:r.label_tx_hash)??"Tx Hash",`${js(s.chainId,s.txHash)}
2209
+ <button class="__crossx-copy-btn" data-copy="${v(s.txHash)}" title="Copy hash">${Te}</button>`):"",c=s.total?`<div class="__crossx-total-pill">
2210
+ <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>
2211
+ <span class="__crossx-total-amount">${v(s.total)}</span>
2212
+ </div>`:"",l=document.createElement("div");return l.id=te,l.innerHTML=`
2177
2213
  <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2178
2214
  <div class="__crossx-header">
2179
- <p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
2215
+ <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_success)??"Transaction complete")}</p>
2180
2216
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2181
2217
  </div>
2182
2218
  <hr class="__crossx-divider">
2183
2219
  <div class="__crossx-body">
2184
2220
  <div class="__crossx-rows">
2185
- ${s}
2186
2221
  ${t}
2187
2222
  ${n}
2188
2223
  ${i}
2189
2224
  ${o}
2225
+ ${a}
2190
2226
  </div>
2191
- ${a}
2192
- <button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
2227
+ ${c}
2228
+ <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((r==null?void 0:r.tx_complete_done_button)??"All Done")}</button>
2193
2229
  </div>
2194
2230
  </div>
2195
- `,c}function ha(r,e){const s=document.createElement("div");return s.id=ee,s.innerHTML=`
2231
+ `,l}function ga(s,e,r){const t=document.createElement("div");return t.id=te,t.innerHTML=`
2196
2232
  <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2197
2233
  <div class="__crossx-header">
2198
- <p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
2234
+ <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.tx_progress_waiting_title)??"Waiting for confirmation")}</p>
2199
2235
  </div>
2200
2236
  <hr class="__crossx-divider">
2201
2237
  <div class="__crossx-body" id="__crossx-progress-body">
2202
2238
  <div class="__crossx-progress-center">
2203
2239
  <div class="__crossx-spinner"></div>
2204
- <p class="__crossx-progress-text">Waiting for transaction receipt...</p>
2240
+ <p class="__crossx-progress-text">${v((r==null?void 0:r.tx_progress_waiting_text)??"Waiting for transaction receipt...")}</p>
2205
2241
  </div>
2206
2242
  </div>
2207
2243
  </div>
2208
- `,s}function pa(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=r.querySelector("#__crossx-ttl"),o=r.querySelector(".__crossx-header");if(i){const g=n?ra:t?"":sa,b=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";g?(i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.innerHTML=`${g}<span>${b}</span>`):i.textContent=b}if(o&&!r.querySelector("#__crossx-close-btn")){const g=document.createElement("button");g.className="__crossx-close",g.id="__crossx-close-btn",g.setAttribute("aria-label","Close"),g.innerHTML=oe,o.appendChild(g)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?J("From",`${St(e.from)}
2209
- <button class="__crossx-copy-btn" data-copy="${N(e.from)}" title="Copy address">${Te}</button>`):"",l=e.to?J("To",`${St(e.to)}
2210
- <button class="__crossx-copy-btn" data-copy="${N(e.to)}" title="Copy address">${Te}</button>`):"",u=e.amount?J("Transfer",`<span>${N(e.amount)}</span>`):"",p=e.fees?J("Tx Fee",`<span>${N(e.fees)}</span>`):"",x=e.txHash?J("Tx Hash",`${zr(e.chainId,e.txHash)}
2211
- <button class="__crossx-copy-btn" data-copy="${N(e.txHash)}" title="Copy hash">${Te}</button>`):"",f=e.total?`<div class="__crossx-total-pill">
2212
- <span class="__crossx-total-label">Total<br>(including fees)</span>
2213
- <span class="__crossx-total-amount">${N(e.total)}</span>
2214
- </div>`:"";a.innerHTML=`
2244
+ `,t}function xa(s,e,r,t){const n=e.status!=="reverted"&&e.status!=="timeout",i=e.status==="timeout",o=s.querySelector("#__crossx-ttl"),a=s.querySelector(".__crossx-header");if(o){const w=i?aa:n?"":oa,E=i?(t==null?void 0:t.tx_timeout)??"Transaction timeout":n?(t==null?void 0:t.tx_success)??"Transaction complete":(t==null?void 0:t.tx_failed)??"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${v(E)}</span>`):o.textContent=E}if(a&&!s.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=oe,a.appendChild(w)}const c=s.querySelector("#__crossx-progress-body");if(!c)return;const l=e.from?J((t==null?void 0:t.label_from)??"From",`${vt(e.from)}
2245
+ <button class="__crossx-copy-btn" data-copy="${v(e.from)}" title="Copy address">${Te}</button>`):"",u=e.to?J((t==null?void 0:t.label_to)??"To",`${vt(e.to)}
2246
+ <button class="__crossx-copy-btn" data-copy="${v(e.to)}" title="Copy address">${Te}</button>`):"",p=e.amount?J((t==null?void 0:t.label_transfer)??"Transfer",`<span>${v(e.amount)}</span>`):"",g=e.fees?J((t==null?void 0:t.label_tx_fee)??"Tx Fee",`<span>${v(e.fees)}</span>`):"",f=e.txHash?J((t==null?void 0:t.label_tx_hash)??"Tx Hash",`${js(e.chainId,e.txHash)}
2247
+ <button class="__crossx-copy-btn" data-copy="${v(e.txHash)}" title="Copy hash">${Te}</button>`):"",x=e.total?`<div class="__crossx-total-pill">
2248
+ <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>
2249
+ <span class="__crossx-total-amount">${v(e.total)}</span>
2250
+ </div>`:"";c.innerHTML=`
2215
2251
  <div class="__crossx-rows">
2216
- ${c}
2217
2252
  ${l}
2218
2253
  ${u}
2219
2254
  ${p}
2220
- ${x}
2255
+ ${g}
2256
+ ${f}
2221
2257
  </div>
2222
- ${f}
2223
- <button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
2224
- `,a.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",b=>{var A;b.stopPropagation();const v=g.dataset.copy;v&&((A=navigator.clipboard)==null||A.writeText(v).catch(()=>{}))})})}function fa(r,e){const s=e,t=bt(r.dappName),n=N(r.message),i=document.createElement("div");return i.id=ee,i.innerHTML=`
2225
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2258
+ ${x}
2259
+ <button class="__crossx-approve-btn" id="__crossx-done-btn">${v((t==null?void 0:t.tx_complete_done_button)??(n?"All Done":"Done"))}</button>
2260
+ `,c.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",E=>{var C;E.stopPropagation();const I=w.dataset.copy;I&&((C=navigator.clipboard)==null||C.writeText(I).catch(()=>{}))})})}function wa(s,e,r){const t=e,n=St(s.dappName),i=v(s.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
2261
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2226
2262
  <div class="__crossx-header">
2227
- <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
2263
+ <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_message_title)??"Signature Request")}</p>
2228
2264
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2229
2265
  </div>
2230
2266
  <hr class="__crossx-divider">
@@ -2232,36 +2268,36 @@ button.__crossx-connect-other-block:active {
2232
2268
  <div class="__crossx-body-cols">
2233
2269
  <div class="__crossx-col-left">
2234
2270
  <p class="__crossx-sig-subtitle">
2235
- <span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
2271
+ <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2236
2272
  </p>
2237
2273
  <div class="__crossx-addr-pill">
2238
- ${ns}
2239
- <span class="__crossx-addr-pill-text">${fe(r.from)}</span>
2274
+ ${ar}
2275
+ <span class="__crossx-addr-pill-text">${fe(s.from)}</span>
2240
2276
  </div>
2241
- <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
2277
+ <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2242
2278
  </div>
2243
2279
  <hr class="__crossx-divider __crossx-divider--cols">
2244
- <div class="__crossx-msg-raw">${n}</div>
2280
+ <div class="__crossx-msg-raw">${i}</div>
2245
2281
  </div>
2246
2282
  <div class="__crossx-btn-row">
2247
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
2248
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">Confirm</button>
2283
+ <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${v((r==null?void 0:r.cancel)??"Cancel")}</button>
2284
+ <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${v((r==null?void 0:r.confirm)??"Confirm")}</button>
2249
2285
  </div>
2250
2286
  </div>
2251
2287
  </div>
2252
- `,i}function ga(r,e){const s=e,t=bt(r.dappName);let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const i=n.primaryType??"—",o=n.message??{};let a=`
2288
+ `,o}function ma(s,e,r){const t=e,n=St(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=`
2253
2289
  <div class="__crossx-td-row">
2254
- <span class="__crossx-td-label">Primary Type</span>
2255
- <span class="__crossx-td-value">${N(i)}</span>
2256
- </div>`;for(const[l,u]of Object.entries(o)){const p=aa(u),f=oa(u)?`<span class="__crossx-addr-text">${fe(u)}</span>
2257
- <button class="__crossx-copy-btn" data-copy="${N(String(u))}" title="Copy">${Te}</button>`:`<span>${p}</span>`;a+=`
2290
+ <span class="__crossx-td-label">${v((r==null?void 0:r.label_primary_type)??"Primary Type")}</span>
2291
+ <span class="__crossx-td-value">${v(o)}</span>
2292
+ </div>`;for(const[u,p]of Object.entries(a)){const g=ua(p),x=da(p)?`<span class="__crossx-addr-text">${fe(p)}</span>
2293
+ <button class="__crossx-copy-btn" data-copy="${v(String(p))}" title="Copy">${Te}</button>`:`<span>${g}</span>`;c+=`
2258
2294
  <div class="__crossx-td-row">
2259
- <span class="__crossx-td-label">${N(l)}</span>
2260
- <div class="__crossx-td-value">${f}</div>
2261
- </div>`}const c=document.createElement("div");return c.id=ee,c.innerHTML=`
2262
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2295
+ <span class="__crossx-td-label">${v(u)}</span>
2296
+ <div class="__crossx-td-value">${x}</div>
2297
+ </div>`}const l=document.createElement("div");return l.id=te,l.innerHTML=`
2298
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2263
2299
  <div class="__crossx-header">
2264
- <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
2300
+ <p class="__crossx-title" id="__crossx-ttl">${v((r==null?void 0:r.sign_typed_data_title)??"Signature Request")}</p>
2265
2301
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2266
2302
  </div>
2267
2303
  <hr class="__crossx-divider">
@@ -2269,34 +2305,34 @@ button.__crossx-connect-other-block:active {
2269
2305
  <div class="__crossx-body-cols">
2270
2306
  <div class="__crossx-col-left">
2271
2307
  <p class="__crossx-sig-subtitle">
2272
- <span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
2308
+ <span class="__crossx-sig-origin">${v(n)}</span>${v((r==null?void 0:r.signature_requesting)??" is requesting a Signature")}
2273
2309
  </p>
2274
2310
  <div class="__crossx-addr-pill">
2275
- ${ns}
2276
- <span class="__crossx-addr-pill-text">${fe(r.from)}</span>
2311
+ ${ar}
2312
+ <span class="__crossx-addr-pill-text">${fe(s.from)}</span>
2277
2313
  </div>
2278
- <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
2314
+ <p class="__crossx-warning">${v((r==null?void 0:r.signature_warning)??"After you sign, changes or cancellations are not possible.")}</p>
2279
2315
  </div>
2280
2316
  <hr class="__crossx-divider __crossx-divider--cols">
2281
- <div class="__crossx-td-rows">${a}</div>
2317
+ <div class="__crossx-td-rows">${c}</div>
2282
2318
  </div>
2283
2319
  <div class="__crossx-btn-row">
2284
- <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
2285
- <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">Confirm</button>
2320
+ <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">${v((r==null?void 0:r.cancel)??"Cancel")}</button>
2321
+ <button class="__crossx-confirm-btn" id="__crossx-confirm-btn">${v((r==null?void 0:r.confirm)??"Confirm")}</button>
2286
2322
  </div>
2287
2323
  </div>
2288
2324
  </div>
2289
- `,c}const _a=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2325
+ `,l}const ya=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2290
2326
  <line x1="12" y1="5" x2="12" y2="19"/>
2291
2327
  <line x1="5" y1="12" x2="19" y2="12"/>
2292
- </svg>`,xa='<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, #019d92)"/><path d="M7.5 12.5L10.5 15.5L16.5 8.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Jr(r){return r.name||`Account ${r.index+1}`}function ma(){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">${qr}</g></svg>`}const wa=gs().portraitBaseUrl;function ya(r,e){return e.replace("#",""),`${wa}/portrait/evm/${r}.png?size=56`}function Yr(r,e,s){const t=ya(r,s),i=ma().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${t}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function ba(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(o=>{const a=t&&o.address.toLowerCase()===t,c=a?" __crossx-wallet-item--selected":"",l=a?`<span class="__crossx-wallet-selected">Selected</span><span class="__crossx-wallet-check">${xa}</span>`:"";return`<button class="__crossx-wallet-item${c}" data-wallet-index="${o.index}" data-wallet-address="${N(o.address)}">
2293
- ${Yr(o.address,o.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${N(Jr(o))}</span><span class="__crossx-wallet-addr">${fe(o.address)}</span></span>${l}
2294
- </button>`}).join(""),i=document.createElement("div");return i.id=ee,i.innerHTML=`
2328
+ </svg>`,ba='<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, #019d92)"/><path d="M7.5 12.5L10.5 15.5L16.5 8.5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';function Ys(s){return s.name||`Account ${s.index+1}`}function Sa(){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">${zs}</g></svg>`}const va=wr().portraitBaseUrl;function Ea(s,e){const r=e.replace("#","");return`${va}/portrait/evm/${s}.png?size=256&bg=${r}`}function Xs(s,e,r){const t=Ea(s,r),i=Sa().replace(/"/g,"&quot;");return`<span class="__crossx-wallet-avatar"><img class="__crossx-wallet-avatar-img" src="${t}" alt="" onerror="this.style.display='none';this.nextElementSibling.innerHTML='${i}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function Aa(s,e,r,t){const n=r==null?void 0:r.toLowerCase(),i=s.map(a=>{const c=n&&a.address.toLowerCase()===n,l=c?" __crossx-wallet-item--selected":"",u=c?`<span class="__crossx-wallet-selected">${v((t==null?void 0:t.wallet_selector_selected)??"Selected")}</span><span class="__crossx-wallet-check">${ba}</span>`:"";return`<button class="__crossx-wallet-item${l}" data-wallet-index="${a.index}" data-wallet-address="${v(a.address)}">
2329
+ ${Xs(a.address,a.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(Ys(a))}</span><span class="__crossx-wallet-addr">${fe(a.address)}</span></span>${u}
2330
+ </button>`}).join(""),o=document.createElement("div");return o.id=te,o.innerHTML=`
2295
2331
  <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2296
2332
  <div class="__crossx-header">
2297
2333
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
2298
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Select Connected Wallet</p>
2299
- <p class="__crossx-subtitle--body">Please select the wallet you previously used for this game to continue.</p>
2334
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${v((t==null?void 0:t.wallet_selector_title)??"Select Connected Wallet")}</p>
2335
+ <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>
2300
2336
  </div>
2301
2337
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2302
2338
  </div>
@@ -2305,46 +2341,47 @@ button.__crossx-connect-other-block:active {
2305
2341
  <div class="__crossx-body-cols">
2306
2342
  <div class="__crossx-col-left">
2307
2343
  <div class="__crossx-mig-info">
2308
- <p class="__crossx-mig-info-title">Why do I need to select a wallet?</p>
2309
- <p class="__crossx-mig-info-desc">Identifying your previously linked wallet ensures your game progress and assets are synced correctly.</p>
2344
+ <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>
2345
+ <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>
2310
2346
  </div>
2311
2347
  </div>
2312
2348
  <hr class="__crossx-divider __crossx-divider--cols">
2313
2349
  <div class="__crossx-col-right-ws">
2314
2350
  <div class="__crossx-wallet-list" id="__crossx-wallet-list">
2315
- ${n}
2351
+ ${i}
2316
2352
  </div>
2317
2353
  <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2318
- <span class="__crossx-wallet-add-icon">${_a}</span>
2319
- <span class="__crossx-wallet-add-label">add a wallet</span>
2354
+ <span class="__crossx-wallet-add-icon">${ya}</span>
2355
+ <span class="__crossx-wallet-add-label">${v((t==null?void 0:t.wallet_selector_add_button)??"add a wallet")}</span>
2320
2356
  </button>
2357
+ <p class="__crossx-wallet-add-error" id="__crossx-add-wallet-error" role="alert" aria-live="polite" hidden></p>
2321
2358
  </div>
2322
2359
  </div>
2323
2360
  </div>
2324
2361
  </div>
2325
- `,i}const Sa=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2362
+ `,o}const Ia=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2326
2363
  <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"/>
2327
2364
  <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"/>
2328
- </svg>`,va=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2365
+ </svg>`,Ta=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2329
2366
  <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"/>
2330
2367
  <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"/>
2331
2368
  <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"/>
2332
2369
  <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"/>
2333
- </svg>`;function Ea(r){const e=cs(r);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${ta[r]??""}</span><span class="__crossx-connect-other-wallet-name">${N(e)}</span></span>`}function Aa(r){if(r.length===0)return"";const e=n=>Ea(r[n]),s="Supported wallets include ";if(r.length===1)return`${s}${e(0)}.`;if(r.length===2)return`${s}${e(0)} and ${e(1)}.`;if(r.length===3)return`${s}${e(0)}, ${e(1)} and ${e(2)}.`;const t=r.length-3;return`${s}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function Ia(r,e=[]){const s=r,t=N(String(e[0])),n=e.length>0?`
2370
+ </svg>`;function Ra(s){const e=ur(s);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${ia[s]??""}</span><span class="__crossx-connect-other-wallet-name">${v(e)}</span></span>`}function ka(s){if(s.length===0)return"";const e=n=>Ra(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 Oa(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?`
2334
2371
  <div class="__crossx-login-or-divider">
2335
- <hr><span>or</span><hr>
2372
+ <hr><span>${i}</span><hr>
2336
2373
  </div>
2337
- <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${t}" aria-labelledby="__crossx-connect-other-heading">
2374
+ <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${n}" aria-labelledby="__crossx-connect-other-heading">
2338
2375
  <span class="__crossx-connect-other-text">
2339
- <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">Connect with Other Wallets</span>
2340
- <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${Aa(e)}</span>
2376
+ <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>
2377
+ <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${ka(e)}</span>
2341
2378
  </span>
2342
- </button>`:"",i=document.createElement("div");return i.id=ee,i.innerHTML=`
2343
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2379
+ </button>`:"",a=document.createElement("div");return a.id=te,a.innerHTML=`
2380
+ <div class="__crossx-card __crossx-card--migration" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2344
2381
  <div class="__crossx-header">
2345
2382
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
2346
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">CROSS Wallet</p>
2347
- <p class="__crossx-subtitle">Sign in instantly with your social account</p>
2383
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">${v((r==null?void 0:r.login_selector_title)??"CROSS Wallet")}</p>
2384
+ <p class="__crossx-subtitle">${v((r==null?void 0:r.login_selector_subtitle)??"Sign in instantly with your social account")}</p>
2348
2385
  </div>
2349
2386
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2350
2387
  </div>
@@ -2352,43 +2389,43 @@ button.__crossx-connect-other-block:active {
2352
2389
  <div class="__crossx-body">
2353
2390
  <div class="__crossx-login-btn-row">
2354
2391
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
2355
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${Sa}</span>
2356
- <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Apple</span>
2392
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${Ia}</span>
2393
+ <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_apple)??"Sign in with Apple")}</span>
2357
2394
  </button>
2358
2395
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
2359
- <span class="__crossx-login-icon">${va}</span>
2360
- <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Google</span>
2396
+ <span class="__crossx-login-icon">${Ta}</span>
2397
+ <span class="__crossx-login-btn-label">${v((r==null?void 0:r.login_selector_google)??"Sign in with Google")}</span>
2361
2398
  </button>
2362
- </div>${n}
2399
+ </div>${o}
2363
2400
  <p class="__crossx-login-terms">
2364
- By continuing, you agree to NEXUS&nbsp;<a class="__crossx-login-terms-link" href="https://terms.crosstoken.io/docs/cross-terms-of-use" target="_blank" rel="noopener noreferrer">Terms of Service</a>&nbsp;and consent to its&nbsp;<a class="__crossx-login-terms-link" href="https://terms.crosstoken.io/docs/nexus-privacy-policy" target="_blank" rel="noopener noreferrer">Privacy Policy.</a>
2401
+ ${((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.crosstoken.io/docs/cross-terms-of-use" 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.crosstoken.io/docs/nexus-privacy-policy" target="_blank" rel="noopener noreferrer">${v((r==null?void 0:r.login_selector_terms_pp)??"Privacy Policy.")}</a>`)}
2365
2402
  </p>
2366
2403
  </div>
2367
2404
  </div>
2368
- `,i}function Ta(r,e){const s=r,t=document.createElement("div");t.id=ee;const n=N(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
2369
- <p class="__crossx-session-account-label">${N(e.accountLabel)}</p>
2370
- <p class="__crossx-session-account-email">${N(e.email)}</p>
2405
+ `,a}function Ca(s,e){const r=s,t=document.createElement("div");t.id=te;const n=v(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
2406
+ <p class="__crossx-session-account-label">${v(e.accountLabel)}</p>
2407
+ <p class="__crossx-session-account-email">${v(e.email)}</p>
2371
2408
  </div>`:"";return t.innerHTML=`
2372
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
2409
+ <div class="__crossx-card __crossx-card--migration" style="${ae(r)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
2373
2410
  <div class="__crossx-header">
2374
- <p class="__crossx-title" id="__crossx-session-header-title">${N(e.title)}</p>
2411
+ <p class="__crossx-title" id="__crossx-session-header-title">${v(e.title)}</p>
2375
2412
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2376
2413
  </div>
2377
2414
  <hr class="__crossx-divider">
2378
2415
  <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
2379
2416
  <div class="__crossx-session-hero">
2380
- <p class="__crossx-session-hero-title">${N(e.title)}</p>
2417
+ <p class="__crossx-session-hero-title">${v(e.title)}</p>
2381
2418
  <p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
2382
2419
  </div>
2383
2420
  ${i}
2384
2421
  <div class="__crossx-btn-row">
2385
- <button class="__crossx-cancel-btn" id="__crossx-session-signout">${N(e.signOutLabel)}</button>
2386
- <button class="__crossx-confirm-btn" id="__crossx-session-signin">${N(e.signInAgainLabel)}</button>
2422
+ <button class="__crossx-cancel-btn" id="__crossx-session-signout">${v(e.signOutLabel)}</button>
2423
+ <button class="__crossx-confirm-btn" id="__crossx-session-signin">${v(e.signInAgainLabel)}</button>
2387
2424
  </div>
2388
2425
  </div>
2389
2426
  </div>
2390
- `,t}function Ra(r,e=!0){const s=r,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=ee,i.innerHTML=`
2391
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2427
+ `,t}function Pa(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=te,i.innerHTML=`
2428
+ <div class="__crossx-card __crossx-card--migration" style="${ae(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2392
2429
  <div class="__crossx-header">
2393
2430
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
2394
2431
  <p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
@@ -2401,14 +2438,14 @@ button.__crossx-connect-other-block:active {
2401
2438
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
2402
2439
  </div>
2403
2440
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
2404
- <span class="__crossx-recover-icon">${Xo}</span>
2441
+ <span class="__crossx-recover-icon">${ta}</span>
2405
2442
  <span class="__crossx-recover-label">Import from Social Backup</span>
2406
2443
  </button>
2407
2444
  ${n}
2408
2445
  </div>
2409
2446
  </div>
2410
- `,i}function ka(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=ee,p.innerHTML=`
2411
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2447
+ `,i}function Na(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",p=document.createElement("div");return p.id=te,p.innerHTML=`
2448
+ <div class="__crossx-card __crossx-card--migration" style="${ae(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2412
2449
  <div class="__crossx-header">
2413
2450
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2414
2451
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
@@ -2427,7 +2464,7 @@ button.__crossx-connect-other-block:active {
2427
2464
  ${u}
2428
2465
  </div>
2429
2466
  </div>
2430
- `,p}function Oa(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[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 Ca(r,e,s){const t=r,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?Oa(i):null,a=document.createElement("div");return a.id=ee,a.innerHTML=`
2467
+ `,p}function La(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 Da(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?La(i):null,a=document.createElement("div");return a.id=te,a.innerHTML=`
2431
2468
  <div class="__crossx-card __crossx-card--migration" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2432
2469
  <div class="__crossx-header">
2433
2470
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
@@ -2442,20 +2479,20 @@ button.__crossx-connect-other-block:active {
2442
2479
  <div class="__crossx-pin-dot" aria-hidden="true">●</div>
2443
2480
  </div>
2444
2481
  <div class="__crossx-pin-lock-messages">
2445
- <p class="__crossx-pin-lock-message">${n?s:"Please try again after the lock expires."}</p>
2482
+ <p class="__crossx-pin-lock-message">${n?r:"Please try again after the lock expires."}</p>
2446
2483
  ${o?`<p class="__crossx-pin-lock-secondary">(Available from ${o})</p>`:""}
2447
2484
  </div>
2448
2485
  </div>
2449
2486
  </div>
2450
- `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function Na(r){const s=[r.check1,r.check2].map((t,n)=>`
2487
+ `,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const p=setInterval(()=>{Date.now()>=i&&(clearInterval(p),l())},1e3);return()=>clearInterval(p)}}}function $a(s){const r=[s.check1,s.check2].map((t,n)=>`
2451
2488
  <div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
2452
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Ma}</div>
2453
- <span class="__crossx-pw-notice-item-text">${N(t)}</span>
2489
+ <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Fa}</div>
2490
+ <span class="__crossx-pw-notice-item-text">${v(t)}</span>
2454
2491
  </div>
2455
2492
  `).join("");return`
2456
2493
  <div class="__crossx-header">
2457
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${N(r.title)}</p>
2458
- <p class="__crossx-pw-subtitle">${N(r.headerSubtitle)}</p>
2494
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
2495
+ <p class="__crossx-pw-subtitle">${v(s.headerSubtitle)}</p>
2459
2496
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2460
2497
  </div>
2461
2498
  <hr class="__crossx-divider">
@@ -2463,26 +2500,26 @@ button.__crossx-connect-other-block:active {
2463
2500
  <div class="__crossx-pw-fields __crossx-pw-fields--notice">
2464
2501
  <div class="__crossx-pw-notice-header">
2465
2502
  <div class="__crossx-pw-notice-title-row">
2466
- <span class="__crossx-pw-notice-icon">${Ba}</span>
2467
- <p class="__crossx-pw-notice-title">${N(r.noticeTitle)}</p>
2503
+ <span class="__crossx-pw-notice-icon">${Ua}</span>
2504
+ <p class="__crossx-pw-notice-title">${v(s.noticeTitle)}</p>
2468
2505
  </div>
2469
- <p class="__crossx-pw-notice-desc">${N(r.noticeDesc)}</p>
2506
+ <p class="__crossx-pw-notice-desc">${v(s.noticeDesc)}</p>
2470
2507
  </div>
2471
2508
  <div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
2472
- ${s}
2509
+ ${r}
2473
2510
  </div>
2474
2511
  </div>
2475
2512
  <button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
2476
- data-next-label="${N(r.nextButton)}"
2477
- data-submit-label="${N(r.submitButton)}">
2478
- ${N(r.nextButton)}
2513
+ data-next-label="${v(s.nextButton)}"
2514
+ data-submit-label="${v(s.submitButton)}">
2515
+ ${v(s.nextButton)}
2479
2516
  </button>
2480
2517
  </div>
2481
2518
  <div class="__crossx-home-indicator"></div>
2482
- `}function is(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${N(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${N(r.subtitle)}</p>`:"",i=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${N(r.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">
2483
- ${Xr}
2519
+ `}function cr(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">
2520
+ ${Qs}
2484
2521
  <span id="__crossx-pin6-lock-countdown"></span>
2485
- </p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${N(r.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${r.attemptCount}/${r.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(b,v)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${v+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",x=Array.from({length:6},(b,v)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${v}" aria-label="PIN digit ${v+1}"></div>`).join(""),f=e?" --disabled":"",g=`
2522
+ </p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${v(s.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(w,E)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${E+1}"${e?" disabled":""}>`).join(""),p=e?" --locked":"",g=Array.from({length:6},(w,E)=>`<div class="__crossx-pin6-dot${p}" data-dot-index="${E}" aria-label="PIN digit ${E+1}"></div>`).join(""),f=e?" --disabled":"",x=`
2486
2523
  <div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
2487
2524
  <div class="__crossx-pin6-numpad-row">
2488
2525
  <button type="button" class="__crossx-pin6-numpad-key${f}" data-key="1">1</button>
@@ -2502,21 +2539,21 @@ button.__crossx-connect-other-block:active {
2502
2539
  <div class="__crossx-pin6-numpad-row">
2503
2540
  <button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
2504
2541
  <button type="button" class="__crossx-pin6-numpad-key${f}" data-key="0">0</button>
2505
- <button type="button" class="__crossx-pin6-numpad-key --delete${f}" data-key="backspace" aria-label="Delete">${Da}</button>
2542
+ <button type="button" class="__crossx-pin6-numpad-key --delete${f}" data-key="backspace" aria-label="Delete">${Wa}</button>
2506
2543
  </div>
2507
2544
  </div>`;return`
2508
2545
  <div class="__crossx-header">
2509
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${N(r.title)}</p>
2546
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${v(s.title)}</p>
2510
2547
  ${t}
2511
2548
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2512
2549
  </div>
2513
2550
  <hr class="__crossx-divider">
2514
- <div class="__crossx-pin6-body"${s}>
2551
+ <div class="__crossx-pin6-body"${r}>
2515
2552
  ${n}
2516
2553
  <div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
2517
2554
  ${u}
2518
2555
  <div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
2519
- ${x}
2556
+ ${g}
2520
2557
  </div>
2521
2558
  </div>
2522
2559
  ${i}
@@ -2524,19 +2561,21 @@ button.__crossx-connect-other-block:active {
2524
2561
  ${c}
2525
2562
  ${o}
2526
2563
  </div>
2527
- ${g}
2528
- `}function jr(r,e){const s=document.createElement("div");return s.id=ee,s.innerHTML=`
2529
- <div class="__crossx-card __crossx-card--pin6" style="${ae(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2564
+ ${x}
2565
+ `}function Zs(s,e){const r=document.createElement("div");return r.id=te,r.innerHTML=`
2566
+ <div class="__crossx-card __crossx-card--pin6" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2530
2567
  ${e}
2531
2568
  </div>
2532
- `,s}function Pa(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((i,o)=>o===0||i===(s[o-1]+1)%10),n=s.every((i,o)=>o===0||i===(s[o-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function La(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function os(r,e,s,t,n,i,o){var O,B;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),u=()=>r.querySelector("#__crossx-pin6-boxes"),p=()=>r.querySelector("#__crossx-pin6-error"),x=()=>r.querySelector("#__crossx-pin6-lock-msg"),f=()=>r.querySelector("#__crossx-pin6-lock-countdown"),g=()=>r.querySelector(".__crossx-pin6-body"),b=()=>l().map(y=>y.value).join(""),v=()=>Array.from(r.querySelectorAll(".__crossx-pin6-dot")),A=()=>{var E;const y=l(),S=v();if(S.length&&(S.forEach((I,k)=>{const U=!!(y[k]&&y[k].value);I.classList.toggle("--filled",U),I.classList.toggle("--active",!1)}),!a&&!c)){const I=y.findIndex(U=>!U.value);(E=S[I===-1?5:I])==null||E.classList.add("--active")}},R=()=>{r.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(S=>S.classList.toggle("--disabled",a)),v().forEach(S=>S.classList.toggle("--locked",a)),A()},L=y=>{a=y,l().forEach(S=>{S.disabled=y,S.classList.toggle("--locked",y)})},P=()=>r.querySelector("#__crossx-pin6-attempt"),G=()=>{const y=p();y&&(y.textContent="")},q=()=>o??"Your account will be locked after further failures.",te=()=>r.querySelector("#__crossx-pin6-warning"),H=y=>{var E;let S=te();if(!S){S=document.createElement("p"),S.className="__crossx-pin6-warning",S.id="__crossx-pin6-warning";const I=p();I?I.insertAdjacentElement("afterend",S):(E=g())==null||E.appendChild(S)}S.textContent=y},X=()=>{const y=te();y&&(y.textContent="")},se=(y,S)=>{var I;let E=P();if(!E){E=document.createElement("p"),E.className="__crossx-pin6-attempt",E.id="__crossx-pin6-attempt";const k=te()??p();k?k.insertAdjacentElement("afterend",E):(I=g())==null||I.appendChild(E)}E.textContent=`${y}/${S}`},F=()=>{const y=P();y&&(y.textContent="")},D=y=>{const S=p();S&&(S.textContent=y);const E=u();E==null||E.classList.add("--shake"),setTimeout(()=>E==null?void 0:E.classList.remove("--shake"),500),l().forEach(I=>{I.value=""}),setTimeout(()=>{var I;(I=l()[0])==null||I.focus(),A()},50)},$=y=>{var U;L(!0),l().forEach(W=>{W.value=""}),R();const S=p();if(S&&(S.textContent="Too many failed attempts. Please wait."),!x()){const W=document.createElement("p");W.className="__crossx-pin6-lock-msg",W.id="__crossx-pin6-lock-msg",W.innerHTML=`${Xr}<span id="__crossx-pin6-lock-countdown"></span>`;const M=p();M?M.insertAdjacentElement("afterend",W):(U=g())==null||U.appendChild(W)}const E=()=>{var K;const W=y-Date.now(),M=f();W<=0?(clearInterval(I),L(!1),(K=x())==null||K.remove(),S&&(S.textContent=""),R(),setTimeout(()=>{var j;return(j=l()[0])==null?void 0:j.focus()},50)):M&&(M.textContent=` ${La(W)}`)},I=setInterval(E,1e3);E();const k=new MutationObserver(()=>{document.contains(r)||(clearInterval(I),k.disconnect())});k.observe(document.body,{childList:!0,subtree:!1})},m=async()=>{if(a||c)return;const y=b();if(y.length===6){c=!0,l().forEach(S=>{S.disabled=!0});try{if(n){const S=await n(y);S.ok?e(y):S.lockExpiresAt?(F(),$(S.lockExpiresAt)):(D(S.error??"Incorrect PIN. Please try again."),S.attemptCount!=null&&S.maxAttempts!=null?(H(q()),se(S.attemptCount,S.maxAttempts)):(X(),F()))}else e(y)}catch(S){t&&t(S)}finally{c=!1,a||l().forEach(S=>{S.disabled=!1}),A()}}};i&&i>Date.now()?$(i):setTimeout(()=>{var y;return(y=l()[0])==null?void 0:y.focus()},100);const w=()=>{if(a||c)return;const y=l(),S=y.find(E=>!E.value)??y[y.length-1];S==null||S.focus()};(O=u())==null||O.addEventListener("click",y=>{y.target.classList.contains("__crossx-pin6-box")||w()}),(B=g())==null||B.addEventListener("click",y=>{const S=y.target;S.classList.contains("__crossx-pin6-box")||S.closest("button")||w()}),l().forEach((y,S)=>{y.addEventListener("input",()=>{var I;const E=y.value.replace(/\D/g,"").slice(-1);y.value=E,G(),E&&S<5&&((I=l()[S+1])==null||I.focus()),A(),b().length===6&&setTimeout(m,80)}),y.addEventListener("keydown",E=>{var I,k;if(E.key==="Backspace"){if(E.preventDefault(),y.value)y.value="";else if(S>0){const U=l()[S-1];U.value="",U.focus()}A()}else E.key==="ArrowLeft"&&S>0?(E.preventDefault(),(I=l()[S-1])==null||I.focus()):E.key==="ArrowRight"&&S<5?(E.preventDefault(),(k=l()[S+1])==null||k.focus()):E.key==="Escape"&&s()}),y.addEventListener("paste",E=>{var U,W;E.preventDefault();const I=(((U=E.clipboardData)==null?void 0:U.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const k=l();I.split("").forEach((M,K)=>{k[K]&&(k[K].value=M)}),(W=k[Math.min(I.length-1,5)])==null||W.focus(),G(),A(),b().length===6&&setTimeout(m,80)}),y.addEventListener("focus",()=>y.select())});const T=r.querySelector("#__crossx-pin6-numpad");if(T){let y=null;const S=()=>{y&&(y.classList.remove("--pressed"),y=null)};T.addEventListener("pointerdown",I=>{const k=I.target.closest(".__crossx-pin6-numpad-key");!k||a||c||(S(),y=k,k.classList.add("--pressed"),k.setPointerCapture(I.pointerId))});const E=I=>{const k=I.dataset.key;if(!k)return;if(k==="backspace"){const K=[...l()].reverse().find(j=>j.value);K&&(K.value="",G()),A();return}if(!/^\d$/.test(k))return;const W=l().find(M=>!M.value);W&&(W.value=k,G(),A(),b().length===6&&setTimeout(m,80))};T.addEventListener("pointerup",I=>{if(!y)return;const k=y;S();const U=k.getBoundingClientRect();I.clientX>=U.left&&I.clientX<=U.right&&I.clientY>=U.top&&I.clientY<=U.bottom&&!a&&!c&&E(k)}),T.addEventListener("pointercancel",S),T.addEventListener("pointerleave",S,!0),A(),i&&i>Date.now()&&R()}}const Da=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
2569
+ `,r}function Ma(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 Ba(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 lr(s,e,r,t,n,i,o){var P,M;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),u=()=>s.querySelector("#__crossx-pin6-boxes"),p=()=>s.querySelector("#__crossx-pin6-error"),g=()=>s.querySelector("#__crossx-pin6-lock-msg"),f=()=>s.querySelector("#__crossx-pin6-lock-countdown"),x=()=>s.querySelector(".__crossx-pin6-body"),w=()=>l().map(b=>b.value).join(""),E=()=>Array.from(s.querySelectorAll(".__crossx-pin6-dot")),I=()=>{var A;const b=l(),S=E();if(S.length&&(S.forEach((T,O)=>{const H=!!(b[O]&&b[O].value);T.classList.toggle("--filled",H),T.classList.toggle("--active",!1)}),!a&&!c)){const T=b.findIndex(H=>!H.value);(A=S[T===-1?5:T])==null||A.classList.add("--active")}},C=()=>{s.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(S=>S.classList.toggle("--disabled",a)),E().forEach(S=>S.classList.toggle("--locked",a)),I()},k=b=>{a=b,l().forEach(S=>{S.disabled=b,S.classList.toggle("--locked",b)})},L=()=>s.querySelector("#__crossx-pin6-attempt"),B=()=>{const b=p();b&&(b.textContent="")},K=()=>o??"Your account will be locked after further failures.",Q=()=>s.querySelector("#__crossx-pin6-warning"),G=b=>{var A;let S=Q();if(!S){S=document.createElement("p"),S.className="__crossx-pin6-warning",S.id="__crossx-pin6-warning";const T=p();T?T.insertAdjacentElement("afterend",S):(A=x())==null||A.appendChild(S)}S.textContent=b},X=()=>{const b=Q();b&&(b.textContent="")},re=(b,S)=>{var T;let A=L();if(!A){A=document.createElement("p"),A.className="__crossx-pin6-attempt",A.id="__crossx-pin6-attempt";const O=Q()??p();O?O.insertAdjacentElement("afterend",A):(T=x())==null||T.appendChild(A)}A.textContent=`${b}/${S}`},U=()=>{const b=L();b&&(b.textContent="")},D=b=>{const S=p();S&&(S.textContent=b);const A=u();A==null||A.classList.add("--shake"),setTimeout(()=>A==null?void 0:A.classList.remove("--shake"),500),l().forEach(T=>{T.value=""}),setTimeout(()=>{var T;(T=l()[0])==null||T.focus(),I()},50)},W=b=>{var H;k(!0),l().forEach(F=>{F.value=""}),C();const S=p();if(S&&(S.textContent="Too many failed attempts. Please wait."),!g()){const F=document.createElement("p");F.className="__crossx-pin6-lock-msg",F.id="__crossx-pin6-lock-msg",F.innerHTML=`${Qs}<span id="__crossx-pin6-lock-countdown"></span>`;const $=p();$?$.insertAdjacentElement("afterend",F):(H=x())==null||H.appendChild(F)}const A=()=>{var q;const F=b-Date.now(),$=f();F<=0?(clearInterval(T),k(!1),(q=g())==null||q.remove(),S&&(S.textContent=""),C(),setTimeout(()=>{var Y;return(Y=l()[0])==null?void 0:Y.focus()},50)):$&&($.textContent=` ${Ba(F)}`)},T=setInterval(A,1e3);A();const O=new MutationObserver(()=>{document.contains(s)||(clearInterval(T),O.disconnect())});O.observe(document.body,{childList:!0,subtree:!1})},m=async()=>{if(a||c)return;const b=w();if(b.length===6){c=!0,l().forEach(S=>{S.disabled=!0});try{if(n){const S=await n(b);S.ok?e(b):S.lockExpiresAt?(U(),W(S.lockExpiresAt)):(D(S.error??"Incorrect PIN. Please try again."),S.attemptCount!=null&&S.maxAttempts!=null?(G(K()),re(S.attemptCount,S.maxAttempts)):(X(),U()))}else e(b)}catch(S){t&&t(S)}finally{c=!1,a||l().forEach(S=>{S.disabled=!1}),I()}}};i&&i>Date.now()?W(i):setTimeout(()=>{var b;return(b=l()[0])==null?void 0:b.focus()},100);const y=()=>{if(a||c)return;const b=l(),S=b.find(A=>!A.value)??b[b.length-1];S==null||S.focus()};(P=u())==null||P.addEventListener("click",b=>{b.target.classList.contains("__crossx-pin6-box")||y()}),(M=x())==null||M.addEventListener("click",b=>{const S=b.target;S.classList.contains("__crossx-pin6-box")||S.closest("button")||y()}),l().forEach((b,S)=>{b.addEventListener("input",()=>{var T;const A=b.value.replace(/\D/g,"").slice(-1);b.value=A,B(),A&&S<5&&((T=l()[S+1])==null||T.focus()),I(),w().length===6&&setTimeout(m,80)}),b.addEventListener("keydown",A=>{var T,O;if(A.key==="Backspace"){if(A.preventDefault(),b.value)b.value="";else if(S>0){const H=l()[S-1];H.value="",H.focus()}I()}else A.key==="ArrowLeft"&&S>0?(A.preventDefault(),(T=l()[S-1])==null||T.focus()):A.key==="ArrowRight"&&S<5?(A.preventDefault(),(O=l()[S+1])==null||O.focus()):A.key==="Escape"&&r()}),b.addEventListener("paste",A=>{var H,F;A.preventDefault();const T=(((H=A.clipboardData)==null?void 0:H.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!T)return;const O=l();T.split("").forEach(($,q)=>{O[q]&&(O[q].value=$)}),(F=O[Math.min(T.length-1,5)])==null||F.focus(),B(),I(),w().length===6&&setTimeout(m,80)}),b.addEventListener("focus",()=>b.select())});const R=s.querySelector("#__crossx-pin6-numpad");if(R){let b=null;const S=()=>{b&&(b.classList.remove("--pressed"),b=null)};R.addEventListener("pointerdown",T=>{const O=T.target.closest(".__crossx-pin6-numpad-key");!O||a||c||(S(),b=O,O.classList.add("--pressed"),O.setPointerCapture(T.pointerId))});const A=T=>{const O=T.dataset.key;if(!O)return;if(O==="backspace"){const q=[...l()].reverse().find(Y=>Y.value);q&&(q.value="",B()),I();return}if(!/^\d$/.test(O))return;const F=l().find($=>!$.value);F&&(F.value=O,B(),I(),w().length===6&&setTimeout(m,80))};R.addEventListener("pointerup",T=>{if(!b)return;const O=b;S();const H=O.getBoundingClientRect();T.clientX>=H.left&&T.clientX<=H.right&&T.clientY>=H.top&&T.clientY<=H.bottom&&!a&&!c&&A(O)}),R.addEventListener("pointercancel",S),R.addEventListener("pointerleave",S,!0),I(),i&&i>Date.now()&&C()}}const Wa=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
2533
2570
  <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"/>
2534
2571
  <line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
2535
2572
  <line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
2536
- </svg>`,Xr=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
2573
+ </svg>`,Qs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
2537
2574
  <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"/>
2538
- </svg>`,Ma=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
2575
+ </svg>`,Fa=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
2539
2576
  <path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
2540
- </svg>`,Ba=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2577
+ </svg>`,Ua=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2541
2578
  <path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="currentColor"/>
2542
- </svg>`;function $a(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((x,f)=>{t[f]&&(t[f].value=x)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.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 Wa{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Fr(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Fr(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var b;he();const i=[...e],o=ba(i,this.tokens,t),a=Xe();pe(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},u=v=>{l(),n(v)},p=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(v=>{v.addEventListener("click",()=>{const A=v.dataset.walletAddress??"",R=parseInt(v.dataset.walletIndex??"0",10),L=i.find(P=>P.index===R);u({address:A,index:R,name:L==null?void 0:L.name})})})})();const f=o.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.disabled=!0;try{const v=await s();i.push(v);const A=o.querySelector("#__crossx-wallet-list");if(A){const R=document.createElement("button");R.className="__crossx-wallet-item",R.dataset.walletIndex=String(v.index),R.dataset.walletAddress=v.address,R.innerHTML=`${Yr(v.address,v.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${N(Jr(v))}</span><span class="__crossx-wallet-addr">${fe(v.address)}</span></span>`,R.addEventListener("click",()=>u(v)),A.appendChild(R),R.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(b=o.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",p),o.addEventListener("click",v=>{v.target===o&&p()});const g=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",g),p())};document.addEventListener("keydown",g)})}showLoginSelector(e){var t;const s=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var x,f,g,b;he();const i=Ia(this.tokens,s),o=Xe();pe(i);const a=()=>{i.remove(),o()},c=v=>{a(),n({type:"oauth",provider:v})},l=v=>{a(),n({type:"external",walletId:v})},u=()=>{a(),n(null)};(x=i.querySelector("#__crossx-apple-btn"))==null||x.addEventListener("click",()=>c("apple")),(f=i.querySelector("#__crossx-google-btn"))==null||f.addEventListener("click",()=>c("google")),(g=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||g.addEventListener("click",v=>{const R=v.currentTarget.dataset.walletId??"";R&&l(R)}),(b=i.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",u),i.addEventListener("click",v=>{v.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(v=>{v.addEventListener("click",A=>A.stopPropagation())});const p=v=>{v.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(s=>{var u,p,x;he();const t=this.messages,n=Ta(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=Xe();pe(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(x=n.querySelector("#__crossx-close-btn"))==null||x.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;he();const n=Ra(this.tokens,s);pe(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",x=>{x.target===n&&u()});const p=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(s=>{he();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_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.pinNotice_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.pinNotice_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.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},i={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=jr(this.tokens,Na(n)),c=Xe();pe(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},p=R=>{u(),s(R)},x=()=>{u(),s(null)},f=a.querySelector(".__crossx-card"),g={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},b=R=>{var L;f.innerHTML=is({title:o.title,headerSubtitle:o.headerSubtitle}),(L=f.querySelector("#__crossx-close-btn"))==null||L.addEventListener("click",x),os(f,P=>{P===R?p(R):v(i.mismatchError)},x)},v=R=>{var L;f.innerHTML=is({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:R}),(L=f.querySelector("#__crossx-close-btn"))==null||L.addEventListener("click",x),os(f,P=>{const G=Pa(P,g);G?v(G):b(P)},x)};(()=>{var se;const R=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),L=f.querySelector("#__crossx-pin-notice-next"),P=new Set;L.removeAttribute("disabled");const G=L.dataset.nextLabel??"Next",q=L.dataset.submitLabel??"I Understand",te=()=>{const F=P.size===R.length;L.classList.toggle("--disabled",!F),L.textContent=F?q:G},H=(F,D)=>{if(P.has(D))return;const $=F.querySelector(`#__crossx-notice-check-${D}`);P.add(D),$.classList.add("--checked"),F.setAttribute("aria-checked","true"),te()},X=(F,D)=>{if(!P.has(D))return;const $=F.querySelector(`#__crossx-notice-check-${D}`);P.delete(D),$.classList.remove("--checked"),F.setAttribute("aria-checked","false"),te()};R.forEach(F=>{const D=parseInt(F.dataset.checkIndex??"0",10);F.addEventListener("click",()=>{P.has(D)?X(F,D):H(F,D)}),F.addEventListener("keydown",$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),P.has(D)?X(F,D):H(F,D))})}),L.addEventListener("click",()=>{if(P.size===R.length){v(e==null?void 0:e.errorMessage);return}const F=R.find($=>{const m=parseInt($.dataset.checkIndex??"0",10);return!P.has(m)});if(!F)return;const D=parseInt(F.dataset.checkIndex??"0",10);F.scrollIntoView({behavior:"smooth",block:"nearest"}),F.classList.add("--highlight"),setTimeout(()=>{F.classList.remove("--highlight"),H(F,D)},400)}),(se=f.querySelector("#__crossx-close-btn"))==null||se.addEventListener("click",x)})(),a.addEventListener("click",R=>{R.target===a&&x()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var A;he();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=jr(this.tokens,is({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=Xe();pe(l);let p=!1;const x=()=>{p||(p=!0,l.remove(),u())},f=R=>{x(),s(R)},g=()=>{x(),s(null)},b=R=>{x(),t(R)},v=l.querySelector(".__crossx-card");(A=v.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",g),os(v,f,g,b,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",R=>{R.target===l&&g()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;he();const t=ka(this.tokens,e);pe(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};$a(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;he();const{overlay:n,startCountdown:i}=Ca(this.tokens,e,s);pe(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;he();const t=ua(e,this.tokens);pe(t);const n=()=>t.remove(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var x;u.stopPropagation();const p=l.dataset.copy;p&&((x=navigator.clipboard)==null||x.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{he();const n=ha(e,this.tokens);pe(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,p;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",x=>{x.target===n&&a()});const l=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{o||(pa(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,u,p;he();let t;e.type==="sign-message"?t=fa(e,this.tokens):e.type==="sign-typed-data"?t=ga(e,this.tokens):e.type==="sign"?t=na(e,this.tokens):t=ia(e,this.tokens);const n=Xe();pe(t);const i=()=>{t.remove(),n()},o=()=>{i(),s(!0)},a=()=>{i(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",f=>{var b;f.stopPropagation();const g=x.dataset.copy;g&&((b=navigator.clipboard)==null||b.writeText(g).catch(()=>{}))})}),t.addEventListener("click",x=>{x.target===t&&a()});const c=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Fa{constructor(e,s,t,n=()=>!1){this.browserConfirmation=e,this.getBridge=s,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 s=this.getBridge();if(!s)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 s.requestUserConfirmation(o)}mapToNativeParams(e){const s=e.type;switch(s){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(s)}`)}}async showTransactionComplete(e){if(!this.shouldDelegateToBridge())return this.browserConfirmation.showTransactionComplete(e)}async showTransactionProgress(e,s){if(this.shouldDelegateToBridge()){try{await s}catch{}return}return this.browserConfirmation.showTransactionProgress(e,s)}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,s){return this.browserConfirmation.showRecoveryPinLockedPrompt(e,s)}async showWalletSelector(e,s,t){const n=this.getBridge();if(this.shouldDelegateToBridge()&&(n!=null&&n.showWalletSelector))try{const i=await n.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===i.address.toLowerCase());return{address:i.address,index:(o==null?void 0:o.index)??i.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,s,t)}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,s){return this.browserConfirmation.setTheme(e,s)}setMessages(e){return this.browserConfirmation.setMessages(e)}}class Zr{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Ua(r,e){r.debug;const s=Fe.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},i=t.authMode!=="cookie"&&Es.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Es(r.projectId):new Un,a=new Bo,c=new Uo,l=new Me,u=new Zr,p=new Tt;let x;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),x=new Go(o,p)):(d.log("[CROSSx] Remote Wallet Provider 사용"),x=new Be(n,o,c,u,p));let f=null;const g=()=>{var G;return((G=f==null?void 0:f.isAuthenticatedViaRNBridge)==null?void 0:G.call(f))??!1};x=new Ko(x,()=>{var G;return(G=f==null?void 0:f.getRNBridge)==null?void 0:G.call(f)},g);const b=new rt(n,c),v=new Wa(r.theme??"light",r.themeTokens),A=new Fa(v,()=>{var G;return(G=f==null?void 0:f.getRNBridge)==null?void 0:G.call(f)},()=>typeof window<"u"?window.location.origin:"http://localhost",g),R=e!=null&&e.wrapConfirmation?e.wrapConfirmation(A):A,L=new at(t,n,o,a,c,l,x,u,R,b,p);f=L;const P=L.signInUseCase;return P&&typeof P.setFreshTokenCallback=="function"&&P.setFreshTokenCallback(()=>L.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=L),L}function Ha(r){const e=Ga(r),s=Ka(e),t=JSON.parse(s);Va(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 Ga(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function Ka(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=qa(r);return decodeURIComponent(e)}function qa(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Va(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;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 s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return z.CONNECT_OTHER_WALLET_DISPLAY_ORDER=as,z.CROSSxError=_,z.CROSSxEthereumProvider=ls,z.CROSSxSDK=at,z.ChainId=nn,z.ConnectOtherWalletItem=We,z.ErrorCode=h,z.MNEMONIC_ADDRESS_LIMIT=Rt,z.PinMemoryStore=Tt,z.TokenMemoryStore=Zr,z.createCROSSxSDK=Ua,z.getConnectOtherWalletLabel=cs,z.parseOAuthDeeplink=Ha,Object.defineProperty(z,Symbol.toStringTag,{value:"Module"}),z}({});
2579
+ </svg>`;function Ha(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var p;c.preventDefault();const l=(((p=c.clipboardData)==null?void 0:p.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,f)=>{t[f]&&(t[f].value=g)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Ga{constructor(e="light",r,t=kt){this.theme=e,this.overrides=r,this.tokens=Hs(e,r),this.displayDecimals=t}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=Hs(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise((n,i)=>{var C;he();const o=[...e],a=Aa(o,this.tokens,t,this.messages),c=Xe();pe(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())};let p=null;const g=k=>{u(),n(k)},f=()=>{u(),p?i(p):n(null)};(()=>{a.querySelectorAll(".__crossx-wallet-item").forEach(k=>{k.addEventListener("click",()=>{const L=k.dataset.walletAddress??"",B=parseInt(k.dataset.walletIndex??"0",10),K=o.find(Q=>Q.index===B);g({address:L,index:B,name:K==null?void 0:K.name})})})})();const w=a.querySelector("#__crossx-add-wallet-error"),E=a.querySelector("#__crossx-add-wallet-btn");E&&E.addEventListener("click",async()=>{E.disabled=!0,w&&(w.hidden=!0,w.textContent="");try{const k=await r();o.push(k);const L=a.querySelector("#__crossx-wallet-list");if(L){const B=document.createElement("button");B.className="__crossx-wallet-item",B.dataset.walletIndex=String(k.index),B.dataset.walletAddress=k.address,B.innerHTML=`${Xs(k.address,k.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${v(Ys(k))}</span><span class="__crossx-wallet-addr">${fe(k.address)}</span></span>`,B.addEventListener("click",()=>g(k)),L.appendChild(B);try{B.scrollIntoView({behavior:"smooth",block:"nearest"})}catch{}}E.disabled=!1}catch(k){const L=k instanceof _&&k.code===h.ADDRESS_LIMIT_EXCEEDED,B=this.resolveAddWalletErrorMessage(k);w&&(w.textContent=B,w.hidden=!1),L?(E.disabled=!0,E.setAttribute("aria-disabled","true")):E.disabled=!1,p=k}}),(C=a.querySelector("#__crossx-close-btn"))==null||C.addEventListener("click",f),a.addEventListener("click",k=>{k.target===a&&f()});const I=k=>{k.key==="Escape"&&(document.removeEventListener("keydown",I),f())};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:ot;return((r==null?void 0:r.wallet_selector_add_error_limit_exceeded)??"Account limit reached. Maximum {limit} accounts allowed.").replace("{limit}",String(i))}return(r==null?void 0:r.wallet_selector_add_error_generic)??"Failed to add a new account. Please try again."}showLoginSelector(e){var t;const r=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var g,f,x,w;he();const i=Oa(this.tokens,r,this.messages),o=Xe();pe(i);const a=()=>{i.remove(),o()},c=E=>{a(),n({type:"oauth",provider:E})},l=E=>{a(),n({type:"external",walletId:E})},u=()=>{a(),n(null)};(g=i.querySelector("#__crossx-apple-btn"))==null||g.addEventListener("click",()=>c("apple")),(f=i.querySelector("#__crossx-google-btn"))==null||f.addEventListener("click",()=>c("google")),(x=i.querySelector("#__crossx-connect-other-wallet-btn"))==null||x.addEventListener("click",E=>{const C=E.currentTarget.dataset.walletId??"";C&&l(C)}),(w=i.querySelector("#__crossx-close-btn"))==null||w.addEventListener("click",u),i.addEventListener("click",E=>{E.target===i&&u()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(E=>{E.addEventListener("click",I=>I.stopPropagation())});const p=E=>{E.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showSessionAlert(e){return new Promise(r=>{var u,p,g;he();const t=this.messages,n=Ca(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=Xe();pe(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(p=n.querySelector("#__crossx-session-signin"))==null||p.addEventListener("click",l),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;he();const n=Pa(this.tokens,r);pe(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",g=>{g.target===n&&u()});const p=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)}})}showPinSetupPrompt(e){return new Promise(r=>{he();const t=this.messages,n={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_notice_header_subtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pin_notice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pin_notice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pin_notice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pin_notice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pin_notice_next_button)??"Next",submitButton:(t==null?void 0:t.pin_notice_submit_button)??"I Understand"},i={title:(t==null?void 0:t.pin_setup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pin_setup_header_subtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pin_setup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pin_setup_mismatch_error)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pin_setup_confirm_title)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pin_setup_confirm_subtitle)??"Enter your PIN again to confirm."},a=Zs(this.tokens,$a(n)),c=Xe();pe(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},p=C=>{u(),r(C)},g=()=>{u(),r(null)},f=a.querySelector(".__crossx-card"),x={tooShort:(t==null?void 0:t.pin_validation_too_short)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pin_validation_numbers_only)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pin_validation_repeating_digit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pin_validation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pin_validation_alternating_pattern)??"Repeating patterns (e.g., 121212) are not allowed."},w=C=>{var k;f.innerHTML=cr({title:o.title,headerSubtitle:o.headerSubtitle}),(k=f.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",g),lr(f,L=>{L===C?p(C):E(i.mismatchError)},g)},E=C=>{var k;f.innerHTML=cr({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:C}),(k=f.querySelector("#__crossx-close-btn"))==null||k.addEventListener("click",g),lr(f,L=>{const B=Ma(L,x);B?E(B):w(L)},g)};(()=>{var re;const C=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),k=f.querySelector("#__crossx-pin-notice-next"),L=new Set;k.removeAttribute("disabled");const B=k.dataset.nextLabel??"Next",K=k.dataset.submitLabel??"I Understand",Q=()=>{const U=L.size===C.length;k.classList.toggle("--disabled",!U),k.textContent=U?K:B},G=(U,D)=>{if(L.has(D))return;const W=U.querySelector(`#__crossx-notice-check-${D}`);L.add(D),W.classList.add("--checked"),U.setAttribute("aria-checked","true"),Q()},X=(U,D)=>{if(!L.has(D))return;const W=U.querySelector(`#__crossx-notice-check-${D}`);L.delete(D),W.classList.remove("--checked"),U.setAttribute("aria-checked","false"),Q()};C.forEach(U=>{const D=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{L.has(D)?X(U,D):G(U,D)}),U.addEventListener("keydown",W=>{(W.key===" "||W.key==="Enter")&&(W.preventDefault(),L.has(D)?X(U,D):G(U,D))})}),k.addEventListener("click",()=>{if(L.size===C.length){E(e==null?void 0:e.errorMessage);return}const U=C.find(W=>{const m=parseInt(W.dataset.checkIndex??"0",10);return!L.has(m)});if(!U)return;const D=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),G(U,D)},400)}),(re=f.querySelector("#__crossx-close-btn"))==null||re.addEventListener("click",g)})(),a.addEventListener("click",C=>{C.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var I;he();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=Zs(this.tokens,cr({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=Xe();pe(l);let p=!1;const g=()=>{p||(p=!0,l.remove(),u())},f=C=>{g(),r(C)},x=()=>{g(),r(null)},w=C=>{g(),t(C)},E=l.querySelector(".__crossx-card");(I=E.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",x),lr(E,f,x,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",C=>{C.target===l&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var a;he();const t=Na(this.tokens,e);pe(t);const n=()=>t.remove(),i=c=>{n(),r(c)},o=()=>{n(),r(null)};Ha(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;he();const{overlay:n,startCountdown:i}=Da(this.tokens,e,r);pe(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;he();const t=_a(e,this.tokens,this.messages);pe(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var g;u.stopPropagation();const p=l.dataset.copy;p&&((g=navigator.clipboard)==null||g.writeText(p).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{he();const n=ga(e,this.tokens,this.messages);pe(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,p;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(p=n.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(xa(n,l,this.tokens,this.messages),c())})})}requestConfirmation(e){return new Promise(r=>{var l,u,p;he();let t;e.type==="sign-message"?t=wa(e,this.tokens,this.messages):e.type==="sign-typed-data"?t=ma(e,this.tokens,this.messages):e.type==="sign"?t=ca(e,this.tokens,this.displayDecimals,this.messages):t=la(e,this.tokens,this.displayDecimals,this.messages);const n=Xe();pe(t);const i=()=>{t.remove(),n()},o=()=>{i(),r(!0)},a=()=>{i(),r(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(p=t.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(g=>{g.addEventListener("click",f=>{var w;f.stopPropagation();const x=g.dataset.copy;x&&((w=navigator.clipboard)==null||w.writeText(x).catch(()=>{}))})}),Xo(t),t.addEventListener("click",g=>{g.target===t&&a()});const c=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Ka{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){const n=this.getBridge();if(this.shouldDelegateToBridge()&&(n!=null&&n.showWalletSelector))try{const i=await n.showWalletSelector({requiredAddress:t}),o=e.find(a=>a.address.toLowerCase()===i.address.toLowerCase());return{address:i.address,index:(o==null?void 0:o.index)??i.index,name:o==null?void 0:o.name}}catch{return null}return this.browserConfirmation.showWalletSelector(e,r,t)}async showPinSetupPrompt(e){return this.browserConfirmation.showPinSetupPrompt(e)}async showPinInputPrompt(e){return this.browserConfirmation.showPinInputPrompt(e)}async showSessionAlert(e){return this.browserConfirmation.showSessionAlert(e)}setTheme(e,r){return this.browserConfirmation.setTheme(e,r)}setMessages(e){return this.browserConfirmation.setMessages(e)}}class en{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function qa(s,e){if(!s.projectId)throw new Error(`[CROSSx] Fatal: projectId is required but was not provided.
2580
+ Set the projectId field in SDKConfig when calling createCROSSxSDK().
2581
+ Example: createCROSSxSDK({ projectId: "your-project-id", ... })`);s.debug;const r=Fe.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&Ir.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new Ir(s.projectId):new Kn,a=new Fo,c=new Ko,l=new $e,u=new en,p=new Rt;let g;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),g=new Vo(o,p)):(d.log("[CROSSx] Remote Wallet Provider 사용"),g=new Me(n,o,c,u,p));let f=null;const x=()=>{var B;return((B=f==null?void 0:f.isAuthenticatedViaRNBridge)==null?void 0:B.call(f))??!1};g=new zo(g,()=>{var B;return(B=f==null?void 0:f.getRNBridge)==null?void 0:B.call(f)},x);const w=new st(n,c),E=new Ga(s.theme??"light",s.themeTokens,s.displayDecimals),I=new Ka(E,()=>{var B;return(B=f==null?void 0:f.getRNBridge)==null?void 0:B.call(f)},()=>typeof window<"u"?window.location.origin:"http://localhost",x),C=e!=null&&e.wrapConfirmation?e.wrapConfirmation(I):I,k=new ct(t,n,o,a,c,l,g,u,C,w,p);f=k;const L=k.signInUseCase;return L&&typeof L.setFreshTokenCallback=="function"&&L.setFreshTokenCallback(()=>k.requestFreshFirebaseIdTokenFromBridge()),typeof window<"u"&&(window.__crossxSDK=k),k}function Va(s){const e=za(s),r=Ja(e),t=JSON.parse(r);Ya(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 za(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 Ja(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=ja(s);return decodeURIComponent(e)}function ja(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 Ya(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 z.CONNECT_OTHER_WALLET_DISPLAY_ORDER=dr,z.CROSSxError=_,z.CROSSxEthereumProvider=hr,z.CROSSxSDK=ct,z.ChainId=an,z.ConnectOtherWalletItem=We,z.ErrorCode=h,z.MNEMONIC_ADDRESS_LIMIT=ot,z.PinMemoryStore=Rt,z.TokenMemoryStore=en,z.createCROSSxSDK=qa,z.getConnectOtherWalletLabel=ur,z.parseOAuthDeeplink=Va,Object.defineProperty(z,Symbol.toStringTag,{value:"Module"}),z}({});