@nexus-cross/crossx-sdk-core 2.0.2-beta.3 → 2.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts +1 -0
  2. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts.map +1 -1
  3. package/dist/__tests__/services/AddressResolverService.test.d.ts +2 -0
  4. package/dist/__tests__/services/AddressResolverService.test.d.ts.map +1 -0
  5. package/dist/__tests__/services/AuthGuardService.test.d.ts +2 -0
  6. package/dist/__tests__/services/AuthGuardService.test.d.ts.map +1 -0
  7. package/dist/__tests__/services/StateManager.test.d.ts +2 -0
  8. package/dist/__tests__/services/StateManager.test.d.ts.map +1 -0
  9. package/dist/__tests__/services/TransactionLifecycleService.test.d.ts +2 -0
  10. package/dist/__tests__/services/TransactionLifecycleService.test.d.ts.map +1 -0
  11. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +3 -0
  12. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
  13. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts +1 -0
  14. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts.map +1 -1
  15. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts +1 -0
  16. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
  17. package/dist/adapters/wallet/types.d.ts +1 -0
  18. package/dist/adapters/wallet/types.d.ts.map +1 -1
  19. package/dist/core/config/environments.d.ts +2 -0
  20. package/dist/core/config/environments.d.ts.map +1 -1
  21. package/dist/core/ports/ConfirmationPort.d.ts +3 -0
  22. package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
  23. package/dist/core/ports/WalletProviderPort.d.ts +1 -0
  24. package/dist/core/ports/WalletProviderPort.d.ts.map +1 -1
  25. package/dist/core/types/index.d.ts +2 -1
  26. package/dist/core/types/index.d.ts.map +1 -1
  27. package/dist/crossx.global +179 -136
  28. package/dist/index.cjs +196 -153
  29. package/dist/index.js +2887 -2577
  30. package/dist/sdk/CROSSxSDK.d.ts +14 -111
  31. package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
  32. package/dist/sdk/services/AddressResolverService.d.ts +20 -0
  33. package/dist/sdk/services/AddressResolverService.d.ts.map +1 -0
  34. package/dist/sdk/services/AuthGuardService.d.ts +12 -0
  35. package/dist/sdk/services/AuthGuardService.d.ts.map +1 -0
  36. package/dist/sdk/services/MigrationOrchestrator.d.ts +25 -0
  37. package/dist/sdk/services/MigrationOrchestrator.d.ts.map +1 -0
  38. package/dist/sdk/services/PinOrchestrator.d.ts +28 -0
  39. package/dist/sdk/services/PinOrchestrator.d.ts.map +1 -0
  40. package/dist/sdk/services/SessionOrchestrator.d.ts +38 -0
  41. package/dist/sdk/services/SessionOrchestrator.d.ts.map +1 -0
  42. package/dist/sdk/services/SignatureVerifier.d.ts +8 -0
  43. package/dist/sdk/services/SignatureVerifier.d.ts.map +1 -0
  44. package/dist/sdk/services/SigningOrchestrator.d.ts +24 -0
  45. package/dist/sdk/services/SigningOrchestrator.d.ts.map +1 -0
  46. package/dist/sdk/services/StateManager.d.ts +40 -0
  47. package/dist/sdk/services/StateManager.d.ts.map +1 -0
  48. package/dist/sdk/services/TransactionLifecycleService.d.ts +15 -0
  49. package/dist/sdk/services/TransactionLifecycleService.d.ts.map +1 -0
  50. package/dist/sdk/services/WalletCreationService.d.ts +24 -0
  51. package/dist/sdk/services/WalletCreationService.d.ts.map +1 -0
  52. package/dist/sdk/services/WalletLifecycleService.d.ts +17 -0
  53. package/dist/sdk/services/WalletLifecycleService.d.ts.map +1 -0
  54. package/dist/sdk/services/index.d.ts +12 -0
  55. package/dist/sdk/services/index.d.ts.map +1 -0
  56. package/dist/sdk/utils/amount.d.ts +3 -0
  57. package/dist/sdk/utils/amount.d.ts.map +1 -0
  58. package/dist/sdk/utils/auth.d.ts +2 -0
  59. package/dist/sdk/utils/auth.d.ts.map +1 -0
  60. package/dist/sdk/utils/signature.d.ts +5 -0
  61. package/dist/sdk/utils/signature.d.ts.map +1 -0
  62. package/dist/sdk/utils/typedData.d.ts +8 -0
  63. package/dist/sdk/utils/typedData.d.ts.map +1 -0
  64. package/package.json +1 -1
package/dist/index.cjs CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";var zs=Object.defineProperty;var Vs=(r,e,s)=>e in r?zs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var P=(r,e,s)=>Vs(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const st=require("jose");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.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.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(h||{});class x extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}var Pe=(r=>(r.MetaMask="io.metamask",r.Binance="com.binance.wallet",r.CROSSx="crossx",r))(Pe||{});const js={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},as=["crossx","io.metamask","com.binance.wallet"];function cs(r){return js[r]??r}function Ys(r){return Array.isArray(r.connectOtherWallets)&&r.connectOtherWallets.length>0?[...r.connectOtherWallets]:r.showConnectOtherWallets===!0?[...as]:[]}const Ze={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}},Xs=Object.fromEntries(Object.entries(Ze).map(([r,e])=>[r,e.caipId])),Js=new Map(Object.values(Ze).map(r=>[r.caipId,r]));new Map(Object.values(Ze).map(r=>[r.chainId,r]));const Zs={symbol:"",decimals:18};function rt(r){var e;return((e=Js.get(r))==null?void 0:e.nativeCurrency)??Zs}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 x(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(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 xe=null;function Ot(r){xe=r}const d={info(...r){if(xe){xe.log(...r);return}console.log(...r)},log(...r){if(xe){xe.log(...r);return}},warn(...r){if(xe){xe.warn(...r);return}},error(...r){if(xe){xe.error(...r);return}}},Qs={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
+ "use strict";var Zs=Object.defineProperty;var Qs=(r,e,s)=>e in r?Zs(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var P=(r,e,s)=>Qs(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const rt=require("jose");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.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.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(h||{});class g extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,g.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}var Ce=(r=>(r.MetaMask="io.metamask",r.Binance="com.binance.wallet",r.CROSSx="crossx",r))(Ce||{});const er={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},cs=["crossx","io.metamask","com.binance.wallet"];function ls(r){return er[r]??r}function tr(r){return Array.isArray(r.connectOtherWallets)&&r.connectOtherWallets.length>0?[...r.connectOtherWallets]:r.showConnectOtherWallets===!0?[...cs]:[]}const Qe={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}},sr=Object.fromEntries(Object.entries(Qe).map(([r,e])=>[r,e.caipId])),rr=new Map(Object.values(Qe).map(r=>[r.caipId,r]));new Map(Object.values(Qe).map(r=>[r.chainId,r]));const nr={symbol:"",decimals:18};function nt(r){var e;return((e=rr.get(r))==null?void 0:e.nativeCurrency)??nr}class ds{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 g(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new g(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 fe=null;function Ct(r){fe=r}const d={info(...r){if(fe){fe.log(...r);return}console.log(...r)},log(...r){if(fe){fe.log(...r);return}},warn(...r){if(fe){fe.warn(...r);return}},error(...r){if(fe){fe.error(...r);return}}},or={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:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
2
2
 
3
- 보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},ds={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.
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
4
 
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"},er={ko:Qs,en:ds};function fe(r="en",e){return er[r]??ds}const Pt="crossx_access_token",Ct="crossx_refresh_token",Nt="crossx_user_info",Je=class Je{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}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 x(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let o="/login";n==="google"?o="/google":n==="apple"&&(o="/apple");const{oauthServiceUrl:i}=this.config,a=`${i}${o}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(i).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 o=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(o)?new x(h.OAUTH_POPUP_BLOCKED,o):new x(h.AUTH_FAILED,o)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var o,i,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let p,b,E;try{const A=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(A).join(", ")),b=(o=A.firebase)==null?void 0:o.sign_in_provider;const k=((i=A.firebase)==null?void 0:i.identities)??{};E=A.email??((a=k.email)==null?void 0:a[0]),b==="google.com"?p=(c=k["google.com"])==null?void 0:c[0]:b==="apple.com"&&(p=(l=k["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",b,"hasProviderSub:",!!p,"email:",E??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const A=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",A.sub,"exp:",A.exp,"필드:",Object.keys(A).join(", "));const k=await this.crypto.verifyJWT(f);if(n=k.signatureVerified??!1,!k.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const H=k.payload,M=H.email??E??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",H.email??"(없음)","/ Firebase JWT:",E??"(없음)","/ OAuth 콜백:",s??"(없음)","→",M??"(없음)"),t={id:H.sub,email:M,signInProvider:b,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const A=this.crypto.decodeJWT(e);t={id:A.sub,email:A.email??s,signInProvider:b,providerSub:p},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const S=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,S),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 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 o=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:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{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 o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}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 o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}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)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}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 x&&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`,o={};if(!t){const u=this.tokenStore.get()??"";u&&(o.access_token=u),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data,c=this.extractResponseErrorCode(a);if(c){const u=Je.REFRESH_RELOGIN_CODES.has(c.code);throw new x(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 x(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.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 x&&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 o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.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,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.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(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.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(Nt);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(Pt);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Ct);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Nt),await this.storage.remove(Pt),await this.storage.remove(Ct),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 o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof x&&o.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===h.PROJECT_NOT_REGISTERED||o.code===h.PROJECT_ID_MISSING||o.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};Je.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let pt=Je;class tr{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 sr{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(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 mt{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 o=0;o<s.length;o++)n[o]=s[o]^t[o];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 rr{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={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:o})).data;if(a!=null&&a.error)throw new x(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class nr{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()}}const Ce={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},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"},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"}};function or(r){const e=r.environment;return e&&e in Ce?Ce[e]:null}function ir(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=or(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Ce)return Ce[r]}catch{}return Ce.production}const ar=2e3,Lt=6e4,cr=1e3,lr=1e4,dr="0x77359400",Dt="0x3B9ACA00",$t=130,Mt=6,Bt=18,Ut=3e4,ur=5*60*1e3,hr=30*1e3;function Me(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 V=class V extends nr{constructor(e,s,t,n,o,i,a,c,l,u,f){var _,p;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,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._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Ot(e.logger),this.confirmation=l,this.pinStore=f??new mt,this.chainRegistry=u,this.jsonRpc=new rr(u,o),this.signInUseCase=new pt(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new tr(this.internalConfig,t,c),this.migrateWalletUseCase=new sr(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}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.0.2 초기화 중..."),this.confirmation.setMessages(fe(this._config.locale));try{const n=ir();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 o=this._config.persistWalletPreference!==!1?await this.storage.get(V.WALLET_PREF_KEY).catch(()=>null):null,i=(e==null?void 0:e.preferredWalletIndex)??(o==null?void 0:o.index),a=(e==null?void 0:e.preferredWalletAddress)??(o==null?void 0:o.address),c=await this.signInUseCase.restoreSession();if(c!=null&&c.success)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,i??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(i,a)}catch(u){if(!(u instanceof x&&u.code===h.PIN_CANCELLED))throw u;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,d.info("[CROSSx SDK] v2.0.2 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new x(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:Ys(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new x(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 x?t:new x(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 o=await this.getAddresses(),i=await this.selectWalletIfMultiple(o,s);return{...n,address:(i==null?void 0:i.address)??n.address,addresses:o}}catch(o){throw o instanceof x&&o.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(i=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",i))),o}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof x?s:new x(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new x(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 x?t:new x(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(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 x&&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}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x?s:new x(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(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.ensurePinForSigning();const n=s.length,i={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(i),i},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 x?e:new x(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(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 o=n?"dark":"light";this.applyTheme(o,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(fe(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.setActiveWallet(t.address,0),{address:t.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.setActiveWallet(s.address,0),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.setActiveWallet(n.address,0),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.setActiveWallet(s.address,0),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.setActiveWallet(n.address,0),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({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}))throw new x(h.USER_REJECTED,"User rejected the message signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof x?i:new x(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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");V.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({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}))throw new x(h.USER_REJECTED,"User rejected the typed data signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return V.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(V.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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=rt(e);if(!await this.confirmation.requestConfirmation({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:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return V.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}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 x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=rt(e);if(!await this.confirmation.requestConfirmation({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:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}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??cr,o=lr,i=t.timeoutMs??Lt,a=Date.now()+i;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,o)}throw new x(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var E,S;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??ar,l=o??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??Lt,u=rt(e),f=s.from??"";let _,p;const b=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{_=A;const k=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),H=s.value?BigInt(s.value):0n,M=V.formatTxAmount(s.value,u.symbol,u.decimals),K=V.formatTxAmount("0x"+k.toString(16),u.symbol,u.decimals),q=V.formatTxAmount("0x"+(H+k).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:A.from,to:A.to??s.to,amount:M,fees:K,total:q,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(p=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:f,to:s.to,amount:V.formatTxAmount(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:s.to},b),p)throw p;return{chainId:e,txHash:a,receipt:_}}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 x(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 x?n:new x(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 x(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 o=n instanceof Error?n.message:String(n);throw new x(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${o}`,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 x(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 x(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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(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:V.formatWei(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(Bt),n=s/t,i=(s%t).toString().padStart(Bt,"0").replace(/0+$/,"").slice(0,Mt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new ls(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Mt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});if(f===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const _=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,f,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const p=_.pinStatus;if(i=p.maxAttempts,o=i-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const b=p.lockExpiresAt*1e3,E=Math.max(1,Math.round((b-Date.now())/1e3)),S=E<=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 잠금 — ${E}초, 메시지: ${S}`),await this.confirmation.showRecoveryPinLockedPrompt(E,S),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof x))throw _;if(_.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const p=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:this.userEmail?Me(this.userEmail,p.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),o--;continue}throw this.clearAuthState(),_}if(_.code===h.MIGRATION_PIN_LOCKED){const p=_.details;if(i=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const b=((p==null?void 0:p.lockExpiresAt)??0)*1e3,E=Math.max(1,Math.round((b-Date.now())/1e3)),S=E<=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 이미 잠금 — ${E}초`),await this.confirmation.showRecoveryPinLockedPrompt(E,S),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const f=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof x&&f.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof x&&f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:_.sessionAlert_title,message:_.alert_sessionExpired,email:this.userEmail?Me(this.userEmail,_.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const E=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",E.address),E}catch(E){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",E),E}}throw this.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,s){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,f,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,o?this.estimateGas(e,s):null,i?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const p=_;if(p){const b=Dt;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(b)).toString(16),c.maxPriorityFeePerGas=b,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=dr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Dt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=V.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==$t)throw new x(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${$t} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}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 x(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}setActiveWallet(e,s){this.address=e,this.activeWalletIndex=s,this.emit("addressChanged",{address:e,index:s}),this._config.persistWalletPreference!==!1&&this.storage.set(V.WALLET_PREF_KEY,{index:s,address:e}).catch(()=>{})}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=V.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this._config.persistWalletPreference!==!1&&this.storage.remove(V.WALLET_PREF_KEY).catch(()=>{}),this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){var n,o;this.ensureInitialized();const e=this.providerSub,s=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const i=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(i)}catch(f){throw this.clearAuthState(),f}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((o=a.user)==null?void 0:o.id)??null;if(!(e?!!c&&c===e:s?!!l&&s===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=fe(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?Me(this.userEmail,f.sessionAlert_appleAccount):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(s){const t=fe(this._config.locale??"en"),n=this.userEmail?Me(this.userEmail,t.sessionAlert_appleAccount):void 0;if(s instanceof x&&s.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(s instanceof x&&s.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(!(s instanceof x)||s.code!==h.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new x(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const i=await this.signInAgain();if(!i.success)throw new x(h.SESSION_EXPIRED,i.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new x(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let o,i;this._verifyPinMutex=new Promise((c,l)=>{o=c,i=l});const a=fe(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),o();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.pinStore.clear(),u instanceof x){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 V.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),o()}catch(c){if(c instanceof x&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=fe(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?Me(this.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success)throw i(c),c}throw i(c),c}finally{this._verifyPinMutex=null}}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=V.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...o}=t;return{ok:!1,error:n,...o}}async loadWalletAfterAuth(e,s){if(!this.userId)return;const t=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",t),t!=="exists")return;const n=await this.walletProvider.getAddresses(this.userId);if(n.length>0){const i=s?n.find(l=>l.address.toLowerCase()===s.toLowerCase()):void 0,a=e!==void 0?n.find(l=>l.index===e):void 0,c=i??a??n[0];d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",c.address),this.setActiveWallet(c.address,c.index);return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const o=await this.walletProvider.getAddress(this.userId,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",o.address),this.setActiveWallet(o.address,0)}async withPinRetry(e){const s=fe(this._config.locale??"en");let t=null;try{return await e()}catch(n){if(n instanceof x){if(t=V.parsePinError(n,s),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof x&&(t=V.parsePinError(n,s),t))continue;throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new x(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new x(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Ot(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};V.WALLET_PREF_KEY="wallet_preference",V.OFFCHAIN_CHAIN_ID="0";let Ve=V;class pr{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 nt="crossx-sdk",fr=1,he="data",Ee="keys",We="aes-primary",_r=12;class Ft{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,fr);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(he)||o.createObjectStore(he),o.objectStoreNames.contains(Ee)||o.createObjectStore(Ee)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ee,We);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(Ee,We,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===nt)return null;try{const e=await this.openDB(nt),s=e.transaction([Ee,he],"readonly"),t=s.objectStore(Ee).get(We),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=s.objectStore(he).getAll(),i=s.objectStore(he).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(Ee,We,n);for(let l=0;l<c.length;l++)await this.idbPut(he,String(c[l]),a[l]);return indexedDB.deleteDatabase(nt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(_r);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(he,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(he,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(he,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(he)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function wt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function we(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function z(r,e,s=""){const t=wt(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function us(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");we(r.outputLen),we(r.blockLen)}function Le(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 hs(r,e){z(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 xr(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function De(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function ot(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function pe(r,e){return r<<32-e|r>>>e}const gr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function mr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function wr(r){for(let e=0;e<r.length;e++)r[e]=mr(r[e]);return r}const Ht=gr?r=>r:wr,ps=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",yr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function He(r){if(z(r),ps)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=yr[r[s]];return e}const _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Wt(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function je(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ps)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,o=0;n<s;n++,o+=2){const i=Wt(r.charCodeAt(o)),a=Wt(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];z(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function fs(r,e={}){const s=(n,o)=>r(o).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 _s(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 br=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Sr(r,e,s){return r&e^~r&s}function vr(r,e,s){return r&e^r&s^e&s}class Er{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=ot(this.buffer)}update(e){Le(this),z(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=ot(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Le(this),hs(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,De(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let f=i;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=ot(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 f=0;f<l;f++)a.setUint32(4*f,u[f],o)}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:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=BigInt(2**32-1),Gt=BigInt(32);function Ir(r,e=!1){return e?{h:Number(r&Ge),l:Number(r>>Gt&Ge)}:{h:Number(r>>Gt&Ge)|0,l:Number(r&Ge)|0}}function Ar(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=Ir(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const Tr=(r,e,s)=>r<<s|e>>>32-s,kr=(r,e,s)=>e<<s|r>>>32-s,Rr=(r,e,s)=>e<<s-32|r>>>64-s,Or=(r,e,s)=>r<<s-32|e>>>64-s,Pr=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]),be=new Uint32Array(64);class Cr extends Er{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let f=0;f<16;f++,s+=4)be[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const _=be[f-15],p=be[f-2],b=pe(_,7)^pe(_,18)^_>>>3,E=pe(p,17)^pe(p,19)^p>>>10;be[f]=E+be[f-7]+b+be[f-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const _=pe(a,6)^pe(a,11)^pe(a,25),p=u+_+Sr(a,c,l)+Pr[f]+be[f]|0,E=(pe(t,2)^pe(t,13)^pe(t,22))+vr(t,n,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=n,n=t,t=p+E|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+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,o,i,a,c,l,u)}roundClean(){De(be)}destroy(){this.set(0,0,0,0,0,0,0,0),De(this.buffer)}}class Nr extends Cr{constructor(){super(32);P(this,"A",ye[0]|0);P(this,"B",ye[1]|0);P(this,"C",ye[2]|0);P(this,"D",ye[3]|0);P(this,"E",ye[4]|0);P(this,"F",ye[5]|0);P(this,"G",ye[6]|0);P(this,"H",ye[7]|0)}}const Lr=fs(()=>new Nr,br(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yt=BigInt(0),ft=BigInt(1);function Ye(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function xs(r){if(typeof r=="bigint"){if(!ze(r))throw new Error("positive bigint expected, got "+r)}else we(r);return r}function qe(r){const e=xs(r).toString(16);return e.length&1?"0"+e:e}function gs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?yt:BigInt("0x"+r)}function Qe(r){return gs(He(r))}function ms(r){return gs(He(Dr(z(r)).reverse()))}function bt(r,e){we(e),r=xs(r);const s=je(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function ws(r,e){return bt(r,e).reverse()}function Dr(r){return Uint8Array.from(r)}const ze=r=>typeof r=="bigint"&&yt<=r;function $r(r,e,s){return ze(r)&&ze(e)&&ze(s)&&e<=r&&r<s}function Mr(r,e,s,t){if(!$r(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Br(r){let e;for(e=0;r>yt;r>>=ft,e+=1);return e}const St=r=>(ft<<BigInt(r))-ft;function Ur(r,e,s){if(we(r,"hashLen"),we(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},_=(...S)=>s(l,ve(c,...S)),p=(S=n)=>{l=_(o,S),c=_(),S.length!==0&&(l=_(i,S),c=_())},b=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const A=[];for(;S<e;){c=_();const k=c.slice();A.push(k),S+=c.length}return ve(...A)};return(S,A)=>{f(),p(S);let k;for(;!(k=A(b()));)p();return f(),k}}function vt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function qt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ne=BigInt(0),se=BigInt(1),Te=BigInt(2),ys=BigInt(3),bs=BigInt(4),Ss=BigInt(5),Fr=BigInt(7),vs=BigInt(8),Hr=BigInt(9),Es=BigInt(16);function ue(r,e){const s=r%e;return s>=ne?s:e+s}function ce(r,e,s){let t=r;for(;e-- >ne;)t*=t,t%=s;return t}function Kt(r,e){if(r===ne)throw new Error("invert: expected non-zero number");if(e<=ne)throw new Error("invert: expected positive modulus, got "+e);let s=ue(r,e),t=e,n=ne,o=se;for(;s!==ne;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==se)throw new Error("invert: does not exist");return ue(n,e)}function Et(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function Is(r,e){const s=(r.ORDER+se)/bs,t=r.pow(e,s);return Et(r,t,e),t}function Wr(r,e){const s=(r.ORDER-Ss)/vs,t=r.mul(e,Te),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,Te),n),a=r.mul(o,r.sub(i,r.ONE));return Et(r,a,e),a}function Gr(r){const e=et(r),s=As(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Fr)/Es;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const f=a.mul(l,n),_=a.mul(l,o),p=a.eql(a.sqr(u),c),b=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(_,f,b);const E=a.eql(a.sqr(u),c),S=a.cmov(l,u,E);return Et(a,S,c),S}}function As(r){if(r<ys)throw new Error("sqrt is not defined for small field");let e=r-se,s=0;for(;e%Te===ne;)e/=Te,s++;let t=Te;const n=et(r);for(;zt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Is;let o=n.pow(t,e);const i=(e+se)/Te;return function(c,l){if(c.is0(l))return l;if(zt(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,o),_=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let b=1,E=c.sqr(_);for(;!c.eql(E,c.ONE);)if(b++,E=c.sqr(E),b===u)throw new Error("Cannot find square root");const S=se<<BigInt(u-b-1),A=c.pow(f,S);u=b,f=c.sqr(A),_=c.mul(_,f),p=c.mul(p,A)}return p}}function qr(r){return r%bs===ys?Is:r%vs===Ss?Wr:r%Es===Hr?Gr(r):As(r)}const Kr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Kr.reduce((t,n)=>(t[n]="function",t),e);return vt(r,s),r}function Vr(r,e,s){if(s<ne)throw new Error("invalid exponent, negatives unsupported");if(s===ne)return r.ONE;if(s===se)return e;let t=r.ONE,n=e;for(;s>ne;)s&se&&(t=r.mul(t,n)),n=r.sqr(n),s>>=se;return t}function Ts(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function zt(r,e){const s=(r.ORDER-se)/Te,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function jr(r,e){e!==void 0&&we(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Yr{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ne);P(this,"ONE",se);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var i;if(e<=ne)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=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=jr(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,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 ne<=e&&e<this.ORDER}is0(e){return e===ne}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&se)===se}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 Vr(this,e,s)}div(e,s){return ue(e*Kt(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 Kt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=qr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?ws(e,this.BYTES):bt(e,this.BYTES)}fromBytes(e,s=!1){z(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_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,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?ms(e):Qe(e);if(a&&(c=ue(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Ts(this,e)}cmov(e,s,t){return t?s:e}}function et(r,e={}){return new Yr(r,e)}function ks(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 Rs(r){const e=ks(r);return e+Math.ceil(e/2)}function Xr(r,e,s=!1){z(r);const t=r.length,n=ks(e),o=Rs(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?ms(r):Qe(r),a=ue(i,e-se)+se;return s?ws(a,n):bt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $e=BigInt(0),ke=BigInt(1);function Xe(r,e){const s=e.negate();return r?s:e}function Vt(r,e){const s=Ts(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function Os(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function it(r,e){Os(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=St(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function jt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=ke);const l=e*t,u=l+Math.abs(a)-1,f=a===0,_=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:_,isNegF:p,offsetF:l}}const at=new WeakMap,Ps=new WeakMap;function ct(r){return Ps.get(r)||1}function Yt(r){if(r!==$e)throw new Error("invalid wNAF")}class Jr{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>$e;)s&ke&&(t=t.add(n)),n=n.double(),s>>=ke;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=it(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=it(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:_,offsetF:p}=jt(t,a,i);t=c,u?o=o.add(Xe(_,s[p])):n=n.add(Xe(f,s[l]))}return Yt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=it(e,this.bits);for(let i=0;i<o.windows&&t!==$e;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=jt(t,i,o);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return Yt(t),n}getPrecomputes(e,s,t){let n=at.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),at.set(s,n))),n}cached(e,s,t){const n=ct(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=ct(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){Os(s,this.bits),Ps.set(e,s),at.delete(e)}hasCache(e){return ct(e)!==1}}function Zr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>$e||t>$e;)s&ke&&(o=o.add(n)),t&ke&&(i=i.add(n)),n=n.double(),s>>=ke,t>>=ke;return{p1:o,p2:i}}function Xt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zr(e),e}else return et(r,{isLE:s})}function Qr(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>$e))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Xt(e.p,s.Fp,t),o=Xt(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:o}}function en(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Cs{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(us(e),z(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),De(n)}update(e){return Le(this),this.iHash.update(e),this}digestInto(e){Le(this),z(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,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 Ns=(r,e,s)=>new Cs(r,e).update(s).digest();Ns.create=(r,e)=>new Cs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Jt=(r,e)=>(r+(r>=0?e:-e)/Ls)/e;function tn(r,e,s){const[[t,n],[o,i]]=e,a=Jt(i*r,s),c=Jt(-n*r,s);let l=r-a*t-c*o,u=-a*n-c*i;const f=l<ge,_=u<ge;f&&(l=-l),_&&(u=-u);const p=St(Math.ceil(Br(s)/2))+Ne;if(l<ge||l>=p||u<ge||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:_,k2:u}}function _t(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function lt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Ye(s.lowS,"lowS"),Ye(s.prehash,"prehash"),s.format!==void 0&&_t(s.format),s}class sn extends Error{constructor(e=""){super(e)}}const Se={Err:sn,_tlv:{encode:(r,e)=>{const{Err:s}=Se;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=qe(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?qe(n.length/2|128):"";return qe(r)+o+n+e},decode(r,e){const{Err:s}=Se;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++],o=!!(n&128);let i=0;if(!o)i=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)i=i<<8|u;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=Se;if(r<ge)throw new e("integer: negative integers are not allowed");let s=qe(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}=Se;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 Qe(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Se,n=z(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{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}=Se,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},ge=BigInt(0),Ne=BigInt(1),Ls=BigInt(2),Ke=BigInt(3),rn=BigInt(4);function nn(r,e={}){const s=Qr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;vt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=$s(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,g,m){const{x:T,y:O}=g.toAffine(),D=t.toBytes(T);if(Ye(m,"isCompressed"),m){u();const w=!t.isOdd(O);return ve(Ds(w),D)}else return ve(Uint8Array.of(4),D,t.toBytes(O))}function _($){z($,void 0,"Point");const{publicKey:g,publicKeyUncompressed:m}=l,T=$.length,O=$[0],D=$.subarray(1);if(T===g&&(O===2||O===3)){const w=t.fromBytes(D);if(!t.isValid(w))throw new Error("bad point: is not on curve, wrong x");const y=E(w);let v;try{v=t.sqrt(y)}catch(F){const B=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+B)}u();const I=t.isOdd(v);return(O&1)===1!==I&&(v=t.neg(v)),{x:w,y:v}}else if(T===m&&O===4){const w=t.BYTES,y=t.fromBytes(D.subarray(0,w)),v=t.fromBytes(D.subarray(w,w*2));if(!S(y,v))throw new Error("bad point: is not on curve");return{x:y,y:v}}else throw new Error(`bad point: got length ${T}, expected compressed=${g} or uncompressed=${m}`)}const p=e.toBytes||f,b=e.fromBytes||_;function E($){const g=t.sqr($),m=t.mul(g,$);return t.add(t.add(m,t.mul($,o.a)),o.b)}function S($,g){const m=t.sqr(g),T=E($);return t.eql(m,T)}if(!S(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(o.a,Ke),rn),k=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(A,k)))throw new Error("bad curve params: a or b");function H($,g,m=!1){if(!t.isValid(g)||m&&t.is0(g))throw new Error(`bad point coordinate ${$}`);return g}function M($){if(!($ instanceof J))throw new Error("Weierstrass Point expected")}function K($){if(!c||!c.basises)throw new Error("no endo");return tn($,c.basises,n.ORDER)}const q=qt(($,g)=>{const{X:m,Y:T,Z:O}=$;if(t.eql(O,t.ONE))return{x:m,y:T};const D=$.is0();g==null&&(g=D?t.ONE:t.inv(O));const w=t.mul(m,g),y=t.mul(T,g),v=t.mul(O,g);if(D)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:w,y}}),Q=qt($=>{if($.is0()){if(e.allowInfinityPoint&&!t.is0($.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:m}=$.toAffine();if(!t.isValid(g)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!S(g,m))throw new Error("bad point: equation left != right");if(!$.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function W($,g,m,T,O){return m=new J(t.mul(m.X,$),m.Y,m.Z),g=Xe(T,g),m=Xe(O,m),g.add(m)}const C=class C{constructor(g,m,T){P(this,"X");P(this,"Y");P(this,"Z");this.X=H("x",g),this.Y=H("y",m,!0),this.Z=H("z",T),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){const{x:m,y:T}=g||{};if(!g||!t.isValid(m)||!t.isValid(T))throw new Error("invalid affine point");if(g instanceof C)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(T)?C.ZERO:new C(m,T,t.ONE)}static fromBytes(g){const m=C.fromAffine(b(z(g,void 0,"point")));return m.assertValidity(),m}static fromHex(g){return C.fromBytes(je(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,m=!0){return U.createCache(this,g),m||this.multiply(Ke),this}assertValidity(){Q(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){M(g);const{X:m,Y:T,Z:O}=this,{X:D,Y:w,Z:y}=g,v=t.eql(t.mul(m,y),t.mul(D,O)),I=t.eql(t.mul(T,y),t.mul(w,O));return v&&I}negate(){return new C(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b:m}=o,T=t.mul(m,Ke),{X:O,Y:D,Z:w}=this;let y=t.ZERO,v=t.ZERO,I=t.ZERO,R=t.mul(O,O),F=t.mul(D,D),B=t.mul(w,w),N=t.mul(O,D);return N=t.add(N,N),I=t.mul(O,w),I=t.add(I,I),y=t.mul(g,I),v=t.mul(T,B),v=t.add(y,v),y=t.sub(F,v),v=t.add(F,v),v=t.mul(y,v),y=t.mul(N,y),I=t.mul(T,I),B=t.mul(g,B),N=t.sub(R,B),N=t.mul(g,N),N=t.add(N,I),I=t.add(R,R),R=t.add(I,R),R=t.add(R,B),R=t.mul(R,N),v=t.add(v,R),B=t.mul(D,w),B=t.add(B,B),R=t.mul(B,N),y=t.sub(y,R),I=t.mul(B,F),I=t.add(I,I),I=t.add(I,I),new C(y,v,I)}add(g){M(g);const{X:m,Y:T,Z:O}=this,{X:D,Y:w,Z:y}=g;let v=t.ZERO,I=t.ZERO,R=t.ZERO;const F=o.a,B=t.mul(o.b,Ke);let N=t.mul(m,D),G=t.mul(T,w),X=t.mul(O,y),ie=t.add(m,T),j=t.add(D,w);ie=t.mul(ie,j),j=t.add(N,G),ie=t.sub(ie,j),j=t.add(m,O);let te=t.add(D,y);return j=t.mul(j,te),te=t.add(N,X),j=t.sub(j,te),te=t.add(T,O),v=t.add(w,y),te=t.mul(te,v),v=t.add(G,X),te=t.sub(te,v),R=t.mul(F,j),v=t.mul(B,X),R=t.add(v,R),v=t.sub(G,R),R=t.add(G,R),I=t.mul(v,R),G=t.add(N,N),G=t.add(G,N),X=t.mul(F,X),j=t.mul(B,j),G=t.add(G,X),X=t.sub(N,X),X=t.mul(F,X),j=t.add(j,X),N=t.mul(G,j),I=t.add(I,N),N=t.mul(te,j),v=t.mul(ie,v),v=t.sub(v,N),N=t.mul(ie,G),R=t.mul(te,R),R=t.add(R,N),new C(v,I,R)}subtract(g){return this.add(g.negate())}is0(){return this.equals(C.ZERO)}multiply(g){const{endo:m}=e;if(!n.isValidNot0(g))throw new Error("invalid scalar: out of range");let T,O;const D=w=>U.cached(this,w,y=>Vt(C,y));if(m){const{k1neg:w,k1:y,k2neg:v,k2:I}=K(g),{p:R,f:F}=D(y),{p:B,f:N}=D(I);O=F.add(N),T=W(m.beta,R,B,w,v)}else{const{p:w,f:y}=D(g);T=w,O=y}return Vt(C,[T,O])[0]}multiplyUnsafe(g){const{endo:m}=e,T=this;if(!n.isValid(g))throw new Error("invalid scalar: out of range");if(g===ge||T.is0())return C.ZERO;if(g===Ne)return T;if(U.hasCache(this))return this.multiply(g);if(m){const{k1neg:O,k1:D,k2neg:w,k2:y}=K(g),{p1:v,p2:I}=Zr(C,T,D,y);return W(m.beta,v,I,O,w)}else return U.unsafe(T,g)}toAffine(g){return q(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return i===Ne?!0:g?g(C,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:g}=e;return i===Ne?this:g?g(C,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return Ye(g,"isCompressed"),this.assertValidity(),p(C,this,g)}toHex(g=!0){return He(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(C,"BASE",new C(o.Gx,o.Gy,t.ONE)),P(C,"ZERO",new C(t.ZERO,t.ONE,t.ZERO)),P(C,"Fp",t),P(C,"Fn",n);let J=C;const ee=n.BITS,U=new Jr(J,e.endo?Math.ceil(ee/2):ee);return J.BASE.precompute(8),J}function Ds(r){return Uint8Array.of(r?2:3)}function $s(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function on(r,e={}){const{Fn:s}=r,t=e.randomBytes||_s,n=Object.assign($s(r.Fp,s),{seed:Rs(s.ORDER)});function o(p){try{const b=s.fromBytes(p);return s.isValidNot0(b)}catch{return!1}}function i(p,b){const{publicKey:E,publicKeyUncompressed:S}=n;try{const A=p.length;return b===!0&&A!==E||b===!1&&A!==S?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Xr(z(p,n.seed,"seed"),s.ORDER)}function c(p,b=!0){return r.BASE.multiply(s.fromBytes(p)).toBytes(b)}function l(p){const{secretKey:b,publicKey:E,publicKeyUncompressed:S}=n;if(!wt(p)||"_lengths"in s&&s._lengths||b===E)return;const A=z(p,void 0,"key").length;return A===E||A===S}function u(p,b,E=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(b)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(p);return r.fromBytes(b).multiply(S).toBytes(E)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},_=en(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:r,utils:f,lengths:n})}function an(r,e,s={}){us(e),vt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||_s,n=s.hmac||((g,m)=>Ns(e,g,m)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:p}=on(r,s),b={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=a*Ls<o.ORDER;function S(g){const m=a>>Ne;return g>m}function A(g,m){if(!i.isValidNot0(m))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return m}function k(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function H(g,m){_t(m);const T=p.signature,O=m==="compact"?T:m==="recovered"?T+1:void 0;return z(g,O)}class M{constructor(m,T,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=A("r",m),this.s=A("s",T),O!=null){if(k(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(m,T=b.format){H(m,T);let O;if(T==="der"){const{r:v,s:I}=Se.toSig(z(m));return new M(v,I)}T==="recovered"&&(O=m[0],T="compact",m=m.subarray(1));const D=p.signature/2,w=m.subarray(0,D),y=m.subarray(D,D*2);return new M(i.fromBytes(w),i.fromBytes(y),O)}static fromHex(m,T){return this.fromBytes(je(m),T)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new M(this.r,this.s,m)}recoverPublicKey(m){const{r:T,s:O}=this,D=this.assertRecovery(),w=D===2||D===3?T+a:T;if(!o.isValid(w))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const y=o.toBytes(w),v=r.fromBytes(ve(Ds((D&1)===0),y)),I=i.inv(w),R=q(z(m,void 0,"msgHash")),F=i.create(-R*I),B=i.create(O*I),N=r.BASE.multiplyUnsafe(F).add(v.multiplyUnsafe(B));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return S(this.s)}toBytes(m=b.format){if(_t(m),m==="der")return je(Se.hexFromSig(this));const{r:T,s:O}=this,D=i.toBytes(T),w=i.toBytes(O);return m==="recovered"?(k(),ve(Uint8Array.of(this.assertRecovery()),D,w)):ve(D,w)}toHex(m){return He(this.toBytes(m))}}const K=s.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const T=Qe(m),O=m.length*8-c;return O>0?T>>BigInt(O):T},q=s.bits2int_modN||function(m){return i.create(K(m))},Q=St(c);function W(g){return Mr("num < 2^"+c,g,ge,Q),i.toBytes(g)}function J(g,m){return z(g,void 0,"message"),m?z(e(g),void 0,"prehashed message"):g}function ee(g,m,T){const{lowS:O,prehash:D,extraEntropy:w}=lt(T,b);g=J(g,D);const y=q(g),v=i.fromBytes(m);if(!i.isValidNot0(v))throw new Error("invalid private key");const I=[W(v),W(y)];if(w!=null&&w!==!1){const N=w===!0?t(p.secretKey):w;I.push(z(N,void 0,"extraEntropy"))}const R=ve(...I),F=y;function B(N){const G=K(N);if(!i.isValidNot0(G))return;const X=i.inv(G),ie=r.BASE.multiply(G).toAffine(),j=i.create(ie.x);if(j===ge)return;const te=i.create(X*i.create(F+j*v));if(te===ge)return;let kt=(ie.x===j?0:2)|Number(ie.y&Ne),Rt=te;return O&&S(te)&&(Rt=i.neg(te),kt^=1),new M(j,Rt,E?void 0:kt)}return{seed:R,k2sig:B}}function U(g,m,T={}){const{seed:O,k2sig:D}=ee(g,m,T);return Ur(e.outputLen,i.BYTES,n)(O,D).toBytes(T.format)}function C(g,m,T,O={}){const{lowS:D,prehash:w,format:y}=lt(O,b);if(T=z(T,void 0,"publicKey"),m=J(m,w),!wt(g)){const v=g instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+v)}H(g,y);try{const v=M.fromBytes(g,y),I=r.fromBytes(T);if(D&&v.hasHighS())return!1;const{r:R,s:F}=v,B=q(m),N=i.inv(F),G=i.create(B*N),X=i.create(R*N),ie=r.BASE.multiplyUnsafe(G).add(I.multiplyUnsafe(X));return ie.is0()?!1:i.create(ie.x)===R}catch{return!1}}function $(g,m,T={}){const{prehash:O}=lt(T,b);return m=J(m,O),M.fromBytes(g,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:p,Point:r,sign:U,verify:C,recoverPublicKey:$,Signature:M,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const It={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},cn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Zt=BigInt(2);function ln(r){const e=It.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ce(u,s,e)*u%e,_=ce(f,s,e)*u%e,p=ce(_,Zt,e)*l%e,b=ce(p,n,e)*p%e,E=ce(b,o,e)*b%e,S=ce(E,a,e)*E%e,A=ce(S,c,e)*S%e,k=ce(A,a,e)*E%e,H=ce(k,s,e)*u%e,M=ce(H,i,e)*b%e,K=ce(M,t,e)*l%e,q=ce(K,Zt,e);if(!xt.eql(xt.sqr(q),r))throw new Error("Cannot find square root");return q}const xt=et(It.p,{sqrt:ln}),dn=nn(It,{Fp:xt,endo:cn}),un=an(dn,Lr),hn=BigInt(0),Be=BigInt(1),pn=BigInt(2),fn=BigInt(7),_n=BigInt(256),xn=BigInt(113),Ms=[],Bs=[],Us=[];for(let r=0,e=Be,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Ms.push(2*(5*t+s)),Bs.push((r+1)*(r+2)/2%64);let n=hn;for(let o=0;o<7;o++)e=(e<<Be^(e>>fn)*xn)%_n,e&pn&&(n^=Be<<(Be<<BigInt(o))-Be);Us.push(n)}const Fs=Ar(Us,!0),gn=Fs[0],mn=Fs[1],Qt=(r,e,s)=>s>32?Rr(r,e,s):Tr(r,e,s),es=(r,e,s)=>s>32?Or(r,e,s):kr(r,e,s);function wn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],u=s[c+1],f=Qt(l,u,1)^s[a],_=es(l,u,1)^s[a+1];for(let p=0;p<50;p+=10)r[i+p]^=f,r[i+p+1]^=_}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Bs[i],c=Qt(n,o,a),l=es(n,o,a),u=Ms[i];n=r[u],o=r[u+1],r[u]=c,r[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=gn[t],r[1]^=mn[t]}De(s)}class At{constructor(e,s,t,n=!1,o=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,we(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=xr(this.state)}clone(){return this._cloneInto()}keccak(){Ht(this.state32),wn(this.state32,this.rounds),Ht(this.state32),this.posOut=0,this.pos=0}update(e){Le(this),z(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];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){Le(this,!1),z(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return we(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(hs(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,De(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new At(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const yn=(r,e,s,t={})=>fs(()=>new At(e,r,s),t),ts=yn(1,136,32),bn=60;class Sn{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=st.createRemoteJWKSet(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+bn<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:o}=await st.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{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 st.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
6
- ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=ts(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=vn(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],_=f>=27?f-27:f,E=new un.Signature(ss(l),ss(u)).addRecoveryBit(_).recoverPublicKey(i).toBytes(!1).slice(1),S=ts(E);return"0x"+He(S.slice(12))}}function vn(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 ss(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const En=3e4,In=1e3;class An{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,In*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??En);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 o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Tn=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ie{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=Ie.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.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:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const i=await Ie.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)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:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Ie.generateRandom16Hex(),l=Ie.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",f=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const _=window.open(f,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),M(),t(new Error("Authentication timeout"))},5*60*1e3),b=10,E=30;let S=0,A=null;const k=()=>{clearInterval(H),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),A=setTimeout(()=>{M(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},H=setInterval(()=>{S++;try{_.closed&&(S<=b?k():(M(),t(new Error("로그인이 취소되었습니다"))))}catch{k()}},1e3),M=()=>{clearTimeout(p),clearInterval(H),A&&clearTimeout(A),window.removeEventListener("message",K)},K=q=>{if(q.origin!==e.expectedOrigin)return;if(!Tn.has(q.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",q.origin),M(),t(new Error("Unauthorized OAuth origin"));return}M();const Q=typeof q.data.status=="string",W=Q?q.data.data??{}:q.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Q?"wrapped":"flat",status:Q?q.data.status:"(flat)"});const J=(W==null?void 0:W.state)??q.data.state;if(!J||J!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Q&&q.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",W==null?void 0:W.error),t(new Error((W==null?void 0:W.error)||"Authentication failed"));return}if(!Q&&(W!=null&&W.error)){d.error("[CROSSx] OAuth 실패:",W.error),t(new Error(W.error||"Authentication failed"));return}const ee=W==null?void 0:W.idToken,U=W==null?void 0:W.accessToken,C=U??ee,$=(W==null?void 0:W.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!ee,hasEmail:!!$}),!C){d.error("[CROSSx] 토큰을 찾을 수 없음:",q.data),t(new Error("Token not found in response"));return}const g={token:C,email:$},m=T=>{Ie.verifyIdTokenNonce(T,l).then(()=>s(g)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?m(U):ee?m(ee):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(g)):ee?m(ee):t(new Error("Token not found in response"))};window.addEventListener("message",K)})}}const Ue="crossx_wallet_data",Re="crossx_mock_pin_hash";class kn{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(Ue)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Ue);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(Ue,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Re,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Ue);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()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,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(Re);return s&&s!==e?!1:(s||await this.storage.set(Re,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(h.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Re);if(n&&t&&n!==t)throw new x(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Re,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new x(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 x(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(Ue,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Re,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 Ae{constructor(e,s,t,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Ut))return e;const s=!e||this.tokenStore.isExpiringSoon(Ut);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new x(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,f;const o=await this.ensureValidToken(),i=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const p=(await this.transport.request({url:i,method:e,headers:a,body:t??void 0})).data;if(p&&typeof p.code=="number"){if(p.code<0||p.code>=400){const b=p.message||p.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:p.code,message:b,url:i,method:e});const E=Ae.mapGatewayError(p.code,p.data);if(E===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 x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(E===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new x(h.USER_NOT_FOUND,Ae.getGatewayErrorMessage(p.code,b));const S=E===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:E,A=S===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ae.getGatewayErrorMessage(p.code,b),k=p.data,H=E===h.PIN_LOCKED?Ae.extractLockDetails(k):k??void 0;throw new x(S,A,H)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:p.code,url:i,method:e}),p.data??p}return p}catch(_){if(_ instanceof x)throw _;const p=((l=_.response)==null?void 0:l.status)??_.status;if((p===401||p===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${p} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const b=_.response.data,E=b.message||b.data||"API 요청에 실패했습니다",S=b.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:S,message:E,url:i,method:e,status:(f=_.response)==null?void 0:f.status}),new x(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${S}): ${E}`)}throw _}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let 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 x(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.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}))}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 x(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(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 x(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);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,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).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 x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const o=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new x(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:o,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new x(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 x(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 o=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof o=="number"&&(t.remainingAttempts=o);const i=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof i=="number"&&(t.maxAttempts=i),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-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 Ae.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-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class Fe{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=Fe.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?hr:ur;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 x(Fe.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Fe.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Ze).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 rs="__crossx-confirm-style",Z="__crossx-confirm-overlay",Rn={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 ns(r,e){const s=Rn[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 On=`
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"},ir={ko:or,en:us};function xe(r="en",e){return ir[r]??us}const Nt="crossx_access_token",Lt="crossx_refresh_token",Dt="crossx_user_info",Ze=class Ze{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}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 g(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let o="/login";n==="google"?o="/google":n==="apple"&&(o="/apple");const{oauthServiceUrl:i}=this.config,a=`${i}${o}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(i).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 o=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(o)?new g(h.OAUTH_POPUP_BLOCKED,o):new g(h.AUTH_FAILED,o)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var o,i,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:x}=await this.exchangeFirebaseToken(e,u);let _,p,v;try{const I=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),p=(o=I.firebase)==null?void 0:o.sign_in_provider;const T=((i=I.firebase)==null?void 0:i.identities)??{};v=I.email??((a=T.email)==null?void 0:a[0]),p==="google.com"?_=(c=T["google.com"])==null?void 0:c[0]:p==="apple.com"&&(_=(l=T["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",p,"hasProviderSub:",!!_,"email:",v??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const I=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const T=await this.crypto.verifyJWT(f);if(n=T.signatureVerified??!1,!T.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const H=T.payload,D=H.email??v??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",H.email??"(없음)","/ Firebase JWT:",v??"(없음)","/ OAuth 콜백:",s??"(없음)","→",D??"(없음)"),t={id:H.sub,email:D,signInProvider:p,providerSub:_},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),x&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,x):x&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??s,signInProvider:p,providerSub:_},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const S=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,S),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 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 o=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:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{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 o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}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 o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}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)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}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 g&&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`,o={};if(!t){const u=this.tokenStore.get()??"";u&&(o.access_token=u),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data,c=this.extractResponseErrorCode(a);if(c){const u=Ze.REFRESH_RELOGIN_CODES.has(c.code);throw new g(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 g(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.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof g&&e.code===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 o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.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,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.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(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.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(Dt);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(Nt);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Lt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Dt),await this.storage.remove(Nt),await this.storage.remove(Lt),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 o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof g&&o.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof g&&(o.code===h.PROJECT_NOT_REGISTERED||o.code===h.PROJECT_ID_MISSING||o.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};Ze.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let _t=Ze;class ar{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 cr{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new g(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 yt{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 o=0;o<s.length;o++)n[o]=s[o]^t[o];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 lr{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={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:o})).data;if(a!=null&&a.error)throw new g(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class dr{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()}}const Ne={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 ur(r){const e=r.environment;return e&&e in Ne?Ne[e]:null}function hs(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=ur(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Ne)return Ne[r]}catch{}return Ne.production}const hr=2e3,Mt=6e4,pr=1e3,fr=1e4,_r="0x77359400",$t="0x3B9ACA00",Bt=130,ps=6,Ut=18,Ht=3e4,xr=5*60*1e3,gr=30*1e3;function mr(r){if(!r||r==="0x0"||r==="0x")return"0";try{const e=BigInt(r);if(e===0n)return"0";const s=10n**BigInt(Ut),t=e/s,o=(e%s).toString().padStart(Ut,"0").replace(/0+$/,"").slice(0,ps);return o?`${t}.${o}`:`${t}`}catch{return"?"}}function We(r,e,s){if(!(!r||r==="0x"||r==="0x0"))try{const t=BigInt(r);if(t===0n)return;const n=10n**BigInt(s),o=t/n,a=(t%n).toString().padStart(s,"0").slice(0,ps).replace(/0+$/,"");return`${a?`${o}.${a}`:`${o}`} ${e}`}catch{return}}function wr(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(e.length!==Bt)throw new g(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Bt} hex 문자(65 바이트) 예상, 현재 ${e.length}`)}function yr(r){const e=r.startsWith("0x")?r.slice(2):r;if(!/^[0-9a-fA-F]+$/.test(e))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(e.length<2)throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}function br(r,e){const s=Sr(e);if(r==="0"){if(s!==void 0&&s!==0)throw new g(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 g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${r})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(s!==n)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${s})가 chainId (${r}, 예상값: ${n})와 일치하지 않습니다`)}}function Sr(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 Pe{constructor(e){this.deps=e,this.verifyPinMutex=null}async ensurePinSetup(){if(this.deps.pinStore.has())return;const e=await this.deps.confirmation.showPinSetupPrompt();if(!e)throw new g(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 g(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 o,i;this.verifyPinMutex=new Promise((c,l)=>{o=c,i=l});const a=xe(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 g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),o();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 g){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 Pe.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.deps.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),o()}catch(c){if(c instanceof g&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=xe(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 i(c),c}throw i(c),c}finally{this.verifyPinMutex=null}}async withPinRetry(e){const s=xe(this.deps.getLocale()??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Pe.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 g&&(t=Pe.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=Pe.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...o}=t;return{ok:!1,error:n,...o}}}class vr{constructor(e){this.deps=e}async confirmAndExecuteWithPreparedPin(e){if(!await this.deps.confirmation.requestConfirmation(e.confirmation))throw new g(h.USER_REJECTED,e.rejectedMessage);return this.deps.pinOrchestrator.withPinRetry(async()=>{let t;return this.deps.walletProvider.prepare&&(t=(await this.deps.walletProvider.prepare(e.prepareAction,e.prepareContext)).uuid),await this.deps.pinOrchestrator.ensureVerifiedPin(),e.execute(t)})}}function Er(r){return r==="google"||r==="apple"}class Ar{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=Er(e.loginType)?{provider:e.loginType}:void 0;let o;try{o=await this.deps.executeSignIn(n)}catch(l){throw this.deps.clearAuthState(),l}if(!o.success)return this.deps.clearAuthState(),o;const i=((s=o.user)==null?void 0:s.providerSub)??null,a=((t=o.user)==null?void 0:t.id)??null;if(!(e.providerSub?!!i&&i===e.providerSub:e.userId?!!a&&e.userId===a:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.deps.executeSignOut().catch(()=>{});const l=xe(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(o);try{await this.deps.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),o}finally{this.deps.setRecoveringSession(!1)}}async withSessionRecovery(e){try{return await e()}catch(s){const t=xe(this.deps.getLocale()??"en"),{userEmail:n}=this.deps.getSessionSnapshot(),o=n?this.deps.maskEmail(n,t.sessionAlert_appleAccount):void 0;if(s instanceof g&&s.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.deps.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:o})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(s instanceof g&&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:o})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.deps.clearAuthState(),s}if(!(s instanceof g)||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:o})==="signout")throw this.deps.clearAuthState(),new g(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const a=await this.signInAgain();if(!a.success)throw new g(h.SESSION_EXPIRED,a.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}}class Ir{constructor(e){this.deps=e}async fetchWalletStatus(){if(typeof this.deps.walletProvider.checkWallet=="function")try{return await this.deps.walletProvider.checkWallet()}catch(e){return 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 o=await this.deps.walletProvider.getAddresses(t);if(o.length>0){const a=s?o.find(u=>u.address.toLowerCase()===s.toLowerCase()):void 0,c=e!==void 0?o.find(u=>u.index===e):void 0,l=a??c??o[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 i=await this.deps.walletProvider.getAddress(t,0);d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",i.address),this.deps.setActiveWallet(i.address,0)}}class kr{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,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const u=await this.deps.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});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 f=await((l=(c=this.deps.walletProvider).verifyRecoveryPin)==null?void 0:l.call(c,u,e));if(!f){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=u;break}if(f.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=u;break}const x=f.pinStatus;if(i=x.maxAttempts,o=i-x.remainingAttempts,x.remainingAttempts===0&&x.lockExpiresAt){const _=x.lockExpiresAt*1e3,p=Math.max(1,Math.round((_-Date.now())/1e3)),v=p<=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 잠금 — ${p}초, 메시지: ${v}`),await this.deps.confirmation.showRecoveryPinLockedPrompt(p,v),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(f){if(!(f instanceof g))throw f;if(f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const x=xe(this.deps.getLocale()??"en"),_=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:x.sessionAlert_title,message:x.alert_sessionExpired,email:_?this.deps.maskEmail(_,x.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),o--;continue}throw this.deps.clearAuthState(),f}if(f.code===h.MIGRATION_PIN_LOCKED){const x=f.details;if(i=(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 _=((x==null?void 0:x.lockExpiresAt)??0)*1e3,p=Math.max(1,Math.round((_-Date.now())/1e3)),v=p<=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 이미 잠금 — ${p}초`),await this.deps.confirmation.showRecoveryPinLockedPrompt(p,v),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",f),f}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.deps.pinOrchestrator.ensurePinSetup();const u=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",u.address),u}catch(u){if(u instanceof g&&u.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(u instanceof g&&u.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const f=xe(this.deps.getLocale()??"en"),x=this.deps.getUserEmail();if(await this.deps.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_sessionExpired,email:x?this.deps.maskEmail(x,f.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.deps.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const v=await this.deps.executeMigrate(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",v.address),v}catch(v){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",v),v}}throw this.deps.clearAuthState(),u}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",u),u}}}class Tr{constructor(e){this.deps=e}async withResolvedGasAndFee(e,s){const t=_=>!(_!=null&&_.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!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,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,f,x]=await Promise.all([l?this.deps.jsonRpcCall("eth_getTransactionCount",[l,"pending"],s):null,o?this.deps.estimateGas(e,s):null,i?this.deps.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const _=x;if(_){const p=$t;c.maxFeePerGas=`0x${(BigInt(_)+BigInt(p)).toString(16)}`,c.maxPriorityFeePerGas=p,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",_,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=_r,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=$t,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}}class Rr{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 g(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}}function Or(r){return r?r.includes("google")?"google":r.includes("apple")?"apple":r:null}class Pr{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,o,i,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:((o=e.user)==null?void 0:o.providerSub)??null,loginType:Or((i=e.user)==null?void 0:i.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 Cr{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 g(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 Nr{constructor(e){this.deps=e}ensureInitialized(){if(!this.deps.isInitialized())throw new g(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.deps.isAuthenticated())throw new g(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()를 먼저 호출하세요.")}}class Lr{constructor(e){this.deps=e}async createWallet(){const e=this.deps.getUserId();if(!e)throw new g(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 g(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 g&&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 g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}}function ot(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 Ie=class Ie extends dr{constructor(e,s,t,n,o,i,a,c,l,u,f){var x,_;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Ct(e.logger),this.confirmation=l,this.pinStore=f??new yt,this.stateManager=new Pr({setState:p=>{p.authenticated!==void 0&&(this.authenticated=p.authenticated),p.userId!==void 0&&(this.userId=p.userId),p.address!==void 0&&(this.address=p.address),p.activeWalletIndex!==void 0&&(this.activeWalletIndex=p.activeWalletIndex),p.userEmail!==void 0&&(this.userEmail=p.userEmail),p.providerSub!==void 0&&(this.providerSub=p.providerSub),p.loginType!==void 0&&(this.loginType=p.loginType),p.tokenSignatureVerified!==void 0&&(this.tokenSignatureVerified=p.tokenSignatureVerified)},getIsRecoveringSession:()=>this._isRecoveringSession,emitAddressChanged:({address:p,index:v})=>{this.emit("addressChanged",{address:p,index:v})},emitAuthChanged:({isAuthenticated:p,address:v,userId:S})=>{this.emit("authChanged",{isAuthenticated:p,address:v,userId:S})},shouldPersistWalletPreference:()=>this._config.persistWalletPreference!==!1,walletPreferenceKey:Ie.WALLET_PREF_KEY,storage:this.storage,pinStore:this.pinStore}),this.pinOrchestrator=new Pe({confirmation:this.confirmation,walletProvider:this.walletProvider,pinStore:this.pinStore,getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:ot,signInAgain:()=>this.signInAgain()}),this.signingOrchestrator=new vr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator}),this.walletLifecycleService=new Ir({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getUserId:()=>this.userId,setActiveWallet:(p,v)=>this.setActiveWallet(p,v)}),this.migrationOrchestrator=new kr({confirmation:this.confirmation,walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,executeMigrate:(p,v)=>this.migrateWalletUseCase.execute(p,v),getLocale:()=>this._config.locale,getUserEmail:()=>this.userEmail,maskEmail:ot,signInAgain:()=>this.signInAgain(),clearAuthState:()=>this.clearAuthState(),getAllowSkip:()=>{var p;return((p=this._config.migration)==null?void 0:p.allowSkip)??!0}}),this.transactionLifecycleService=new Tr({getActiveAddress:()=>this.address,estimateGas:(p,v)=>this.estimateGas(p,v),getBaseFeePerGas:p=>this.getBaseFeePerGas(p),jsonRpcCall:(p,v,S)=>this.jsonRpc.call(p,v,S)}),this.signatureVerifier=new Rr(this.crypto),this.addressResolverService=new Cr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,getActiveAddress:()=>this.address,getActiveWalletIndex:()=>this.activeWalletIndex,getUserId:()=>this.userId}),this.authGuardService=new Nr({isInitialized:()=>this.initialized,isAuthenticated:()=>this.authenticated}),this.walletCreationService=new Lr({walletProvider:this.walletProvider,pinOrchestrator:this.pinOrchestrator,migrationOrchestrator:this.migrationOrchestrator,walletLifecycleService:this.walletLifecycleService,getUserId:()=>this.userId,getProviderSub:()=>this.providerSub,setActiveWallet:(p,v)=>this.setActiveWallet(p,v)}),this.sessionOrchestrator=new Ar({ensureInitialized:()=>this.ensureInitialized(),getSessionSnapshot:()=>({providerSub:this.providerSub,userId:this.userId,loginType:this.loginType,userEmail:this.userEmail}),setRecoveringSession:p=>{this._isRecoveringSession=p},setAuthenticated:p=>{this.authenticated=p},clearTokenStore:()=>this.tokenStore.clear(),executeSignIn:p=>this.signInUseCase.execute(p),executeSignOut:()=>this.signOutUseCase.execute(),showSessionAlert:p=>this.confirmation.showSessionAlert(p),clearAuthState:()=>this.clearAuthState(),applyAuthResult:p=>this.applyAuthResult(p),loadWalletAfterAuth:()=>this.walletLifecycleService.loadWalletAfterAuth(),getLocale:()=>this._config.locale,maskEmail:ot}),this.chainRegistry=u,this.jsonRpc=new lr(u,o),this.signInUseCase=new _t(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new ar(this.internalConfig,t,c),this.migrateWalletUseCase=new cr(t,a),(x=a.setOnUnauthorized)==null||x.call(a,()=>this.forceLogout()),(_=a.setTokenRefresher)==null||_.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}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.0.2 초기화 중..."),this.confirmation.setMessages(xe(this._config.locale));try{const n=hs();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 o=this._config.persistWalletPreference!==!1?await this.storage.get(Ie.WALLET_PREF_KEY).catch(()=>null):null,i=(e==null?void 0:e.preferredWalletIndex)??(o==null?void 0:o.index),a=(e==null?void 0:e.preferredWalletAddress)??(o==null?void 0:o.address),c=await this.signInUseCase.restoreSession();if(c!=null&&c.success)if(this.applyAuthResult(c),this.address&&(!a||this.address.toLowerCase()===a.toLowerCase()))this.address&&this.setActiveWallet(this.address,i??this.activeWalletIndex);else try{await this.loadWalletAfterAuth(i,a)}catch(u){if(!(u instanceof g&&u.code===h.PIN_CANCELLED))throw u;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}return this.initialized=!0,d.info("[CROSSx SDK] v2.0.2 초기화 완료"),this.emit("initialized",{restored:!!(c!=null&&c.success)}),c??null}catch(n){throw new g(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:tr(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new g(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 g?t:new g(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 o=await this.getAddresses(),i=await this.selectWalletIfMultiple(o,s);return{...n,address:(i==null?void 0:i.address)??n.address,addresses:o}}catch(o){throw o instanceof g&&o.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(i=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",i))),o}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw s instanceof g?s:new g(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new g(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 g?t:new g(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new g(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 g&&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}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(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 g?s:new g(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(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 g(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,i={address:(await this.pinOrchestrator.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.push(i),i},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 g?e:new g(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof g?s:new g(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 o=n?"dark":"light";this.applyTheme(o,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(xe(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 g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);try{const o=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:i=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,n.address)});return this.signatureVerifier.verifySignatureSigner(s,o.signature,n.address),{chainId:e,signature:o.signature,message:s,address:n.address}}catch(o){throw o instanceof g?o:new g(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}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 g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");br(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);try{const o=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:i=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,i,n.address)});return wr(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof g?o:new g(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,s){return this.signTypedData(Ie.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 g(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 o=nt(e);try{const i=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:o.symbol,nativeDecimals:o.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 yr(i.signature),{chainId:e,signedTx:i.signature,txHash:i.txHash??""}}catch(i){if(i instanceof g)throw i;const a=i instanceof Error?i.message:String(i);throw new g(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${a}`,i)}}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 g(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 o=nt(e);try{const i=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:o.symbol,nativeDecimals:o.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 a=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,a)).txHash;const c=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,a);return c.txHash??c.signature}});return{chainId:e,txHash:i,status:"pending"}}catch(i){if(i instanceof g)throw i;const a=i instanceof Error?i.message:String(i);throw new g(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${a}`,i)}}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??pr,o=fr,i=t.timeoutMs??Mt,a=Date.now()+i;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,o)}throw new g(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var v,S;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??hr,l=o??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??Mt,u=nt(e),f=s.from??"";let x,_;const p=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{x=I;const T=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),H=s.value?BigInt(s.value):0n,D=We(s.value,u.symbol,u.decimals),K=We("0x"+T.toString(16),u.symbol,u.decimals),q=We("0x"+(H+T).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??s.to,amount:D,fees:K,total:q,nativeSymbol:u.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(_=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:f,to:s.to,amount:We(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:s.to},p),_)throw _;return{chainId:e,txHash:a,receipt:x}}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 g(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 g?n:new g(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 g(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 o=n instanceof Error?n.message:String(n);throw new g(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${o}`,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 g(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 g(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 g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(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:mr(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}getProvider(e){return this.ensureAuthenticated(),new ds(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof g)throw n;const o=n instanceof Error?n.message:String(n);throw new g(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}setActiveWallet(e,s){this.stateManager.setActiveWallet(e,s)}applyAuthResult(e){this.stateManager.applyAuthResult(e)}clearAuthState(){this.stateManager.clearAuthState()}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()}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(),Ct(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Ie.WALLET_PREF_KEY="wallet_preference",Ie.OFFCHAIN_CHAIN_ID="0";let je=Ie;class Dr{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 it="crossx-sdk",Mr=1,ue="data",ve="keys",Ge="aes-primary",$r=12;class Ft{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,Mr);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(ue)||o.createObjectStore(ue),o.objectStoreNames.contains(ve)||o.createObjectStore(ve)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(ve,Ge);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(ve,Ge,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===it)return null;try{const e=await this.openDB(it),s=e.transaction([ve,ue],"readonly"),t=s.objectStore(ve).get(Ge),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=s.objectStore(ue).getAll(),i=s.objectStore(ue).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(ve,Ge,n);for(let l=0;l<c.length;l++)await this.idbPut(ue,String(c[l]),a[l]);return indexedDB.deleteDatabase(it),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array($r);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(ue,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(ue,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(ue,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ue)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function bt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function me(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=bt(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function fs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");me(r.outputLen),me(r.blockLen)}function De(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 _s(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 Br(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Me(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function at(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function he(r,e){return r<<32-e|r>>>e}const Ur=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Hr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Fr(r){for(let e=0;e<r.length;e++)r[e]=Hr(r[e]);return r}const Wt=Ur?r=>r:Fr,xs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Wr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Fe(r){if(V(r),xs)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Wr[r[s]];return e}const pe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gt(r){if(r>=pe._0&&r<=pe._9)return r-pe._0;if(r>=pe.A&&r<=pe.F)return r-(pe.A-10);if(r>=pe.a&&r<=pe.f)return r-(pe.a-10)}function Ye(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(xs)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,o=0;n<s;n++,o+=2){const i=Gt(r.charCodeAt(o)),a=Gt(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function Se(...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 o=r[t];s.set(o,n),n+=o.length}return s}function gs(r,e={}){const s=(n,o)=>r(o).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 ms(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 Gr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function qr(r,e,s){return r&e^~r&s}function Kr(r,e,s){return r&e^r&s^e&s}class Vr{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=at(this.buffer)}update(e){De(this),V(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=at(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){De(this),_s(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Me(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let f=i;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=at(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 f=0;f<l;f++)a.setUint32(4*f,u[f],o)}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:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const we=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qe=BigInt(2**32-1),qt=BigInt(32);function zr(r,e=!1){return e?{h:Number(r&qe),l:Number(r>>qt&qe)}:{h:Number(r>>qt&qe)|0,l:Number(r&qe)|0}}function jr(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=zr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const Yr=(r,e,s)=>r<<s|e>>>32-s,Xr=(r,e,s)=>e<<s|r>>>32-s,Jr=(r,e,s)=>e<<s-32|r>>>64-s,Zr=(r,e,s)=>r<<s-32|e>>>64-s,Qr=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]),ye=new Uint32Array(64);class en extends Vr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let f=0;f<16;f++,s+=4)ye[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const x=ye[f-15],_=ye[f-2],p=he(x,7)^he(x,18)^x>>>3,v=he(_,17)^he(_,19)^_>>>10;ye[f]=v+ye[f-7]+p+ye[f-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const x=he(a,6)^he(a,11)^he(a,25),_=u+x+qr(a,c,l)+Qr[f]+ye[f]|0,v=(he(t,2)^he(t,13)^he(t,22))+Kr(t,n,o)|0;u=l,l=c,c=a,a=i+_|0,i=o,o=n,n=t,t=_+v|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+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,o,i,a,c,l,u)}roundClean(){Me(ye)}destroy(){this.set(0,0,0,0,0,0,0,0),Me(this.buffer)}}class tn extends en{constructor(){super(32);P(this,"A",we[0]|0);P(this,"B",we[1]|0);P(this,"C",we[2]|0);P(this,"D",we[3]|0);P(this,"E",we[4]|0);P(this,"F",we[5]|0);P(this,"G",we[6]|0);P(this,"H",we[7]|0)}}const sn=gs(()=>new tn,Gr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const St=BigInt(0),xt=BigInt(1);function Xe(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function ws(r){if(typeof r=="bigint"){if(!ze(r))throw new Error("positive bigint expected, got "+r)}else me(r);return r}function Ke(r){const e=ws(r).toString(16);return e.length&1?"0"+e:e}function ys(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?St:BigInt("0x"+r)}function et(r){return ys(Fe(r))}function bs(r){return ys(Fe(rn(V(r)).reverse()))}function vt(r,e){me(e),r=ws(r);const s=Ye(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function Ss(r,e){return vt(r,e).reverse()}function rn(r){return Uint8Array.from(r)}const ze=r=>typeof r=="bigint"&&St<=r;function nn(r,e,s){return ze(r)&&ze(e)&&ze(s)&&e<=r&&r<s}function on(r,e,s,t){if(!nn(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function an(r){let e;for(e=0;r>St;r>>=xt,e+=1);return e}const Et=r=>(xt<<BigInt(r))-xt;function cn(r,e,s){if(me(r,"hashLen"),me(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},x=(...S)=>s(l,Se(c,...S)),_=(S=n)=>{l=x(o,S),c=x(),S.length!==0&&(l=x(i,S),c=x())},p=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const I=[];for(;S<e;){c=x();const T=c.slice();I.push(T),S+=c.length}return Se(...I)};return(S,I)=>{f(),_(S);let T;for(;!(T=I(p()));)_();return f(),T}}function At(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function Kt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const re=BigInt(0),te=BigInt(1),ke=BigInt(2),vs=BigInt(3),Es=BigInt(4),As=BigInt(5),ln=BigInt(7),Is=BigInt(8),dn=BigInt(9),ks=BigInt(16);function de(r,e){const s=r%e;return s>=re?s:e+s}function ae(r,e,s){let t=r;for(;e-- >re;)t*=t,t%=s;return t}function Vt(r,e){if(r===re)throw new Error("invert: expected non-zero number");if(e<=re)throw new Error("invert: expected positive modulus, got "+e);let s=de(r,e),t=e,n=re,o=te;for(;s!==re;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==te)throw new Error("invert: does not exist");return de(n,e)}function It(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function Ts(r,e){const s=(r.ORDER+te)/Es,t=r.pow(e,s);return It(r,t,e),t}function un(r,e){const s=(r.ORDER-As)/Is,t=r.mul(e,ke),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,ke),n),a=r.mul(o,r.sub(i,r.ONE));return It(r,a,e),a}function hn(r){const e=tt(r),s=Rs(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+ln)/ks;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const f=a.mul(l,n),x=a.mul(l,o),_=a.eql(a.sqr(u),c),p=a.eql(a.sqr(f),c);l=a.cmov(l,u,_),u=a.cmov(x,f,p);const v=a.eql(a.sqr(u),c),S=a.cmov(l,u,v);return It(a,S,c),S}}function Rs(r){if(r<vs)throw new Error("sqrt is not defined for small field");let e=r-te,s=0;for(;e%ke===re;)e/=ke,s++;let t=ke;const n=tt(r);for(;zt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return Ts;let o=n.pow(t,e);const i=(e+te)/ke;return function(c,l){if(c.is0(l))return l;if(zt(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,o),x=c.pow(l,e),_=c.pow(l,i);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let p=1,v=c.sqr(x);for(;!c.eql(v,c.ONE);)if(p++,v=c.sqr(v),p===u)throw new Error("Cannot find square root");const S=te<<BigInt(u-p-1),I=c.pow(f,S);u=p,f=c.sqr(I),x=c.mul(x,f),_=c.mul(_,I)}return _}}function pn(r){return r%Es===vs?Ts:r%Is===As?un:r%ks===dn?hn(r):Rs(r)}const fn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function _n(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=fn.reduce((t,n)=>(t[n]="function",t),e);return At(r,s),r}function xn(r,e,s){if(s<re)throw new Error("invalid exponent, negatives unsupported");if(s===re)return r.ONE;if(s===te)return e;let t=r.ONE,n=e;for(;s>re;)s&te&&(t=r.mul(t,n)),n=r.sqr(n),s>>=te;return t}function Os(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function zt(r,e){const s=(r.ORDER-te)/ke,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function gn(r,e){e!==void 0&&me(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class mn{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",re);P(this,"ONE",te);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var i;if(e<=re)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=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=gn(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return de(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return re<=e&&e<this.ORDER}is0(e){return e===re}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return de(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return de(e*e,this.ORDER)}add(e,s){return de(e+s,this.ORDER)}sub(e,s){return de(e-s,this.ORDER)}mul(e,s){return de(e*s,this.ORDER)}pow(e,s){return xn(this,e,s)}div(e,s){return de(e*Vt(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 Vt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=pn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Ss(e,this.BYTES):vt(e,this.BYTES)}fromBytes(e,s=!1){V(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_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,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?bs(e):et(e);if(a&&(c=de(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Os(this,e)}cmov(e,s,t){return t?s:e}}function tt(r,e={}){return new mn(r,e)}function Ps(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 Cs(r){const e=Ps(r);return e+Math.ceil(e/2)}function wn(r,e,s=!1){V(r);const t=r.length,n=Ps(e),o=Cs(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?bs(r):et(r),a=de(i,e-te)+te;return s?Ss(a,n):vt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $e=BigInt(0),Te=BigInt(1);function Je(r,e){const s=e.negate();return r?s:e}function jt(r,e){const s=Os(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function Ns(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ct(r,e){Ns(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=Et(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Yt(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=Te);const l=e*t,u=l+Math.abs(a)-1,f=a===0,x=a<0,_=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:x,isNegF:_,offsetF:l}}const lt=new WeakMap,Ls=new WeakMap;function dt(r){return Ls.get(r)||1}function Xt(r){if(r!==$e)throw new Error("invalid wNAF")}class yn{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>$e;)s&Te&&(t=t.add(n)),n=n.double(),s>>=Te;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=ct(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=ct(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:x,offsetF:_}=Yt(t,a,i);t=c,u?o=o.add(Je(x,s[_])):n=n.add(Je(f,s[l]))}return Xt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=ct(e,this.bits);for(let i=0;i<o.windows&&t!==$e;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Yt(t,i,o);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return Xt(t),n}getPrecomputes(e,s,t){let n=lt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),lt.set(s,n))),n}cached(e,s,t){const n=dt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=dt(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){Ns(s,this.bits),Ls.set(e,s),lt.delete(e)}hasCache(e){return dt(e)!==1}}function bn(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>$e||t>$e;)s&Te&&(o=o.add(n)),t&Te&&(i=i.add(n)),n=n.double(),s>>=Te,t>>=Te;return{p1:o,p2:i}}function Jt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return _n(e),e}else return tt(r,{isLE:s})}function Sn(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>$e))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Jt(e.p,s.Fp,t),o=Jt(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:o}}function vn(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Ds{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(fs(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 o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Me(n)}update(e){return De(this),this.iHash.update(e),this}digestInto(e){De(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:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,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 Ms=(r,e,s)=>new Ds(r,e).update(s).digest();Ms.create=(r,e)=>new Ds(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Zt=(r,e)=>(r+(r>=0?e:-e)/$s)/e;function En(r,e,s){const[[t,n],[o,i]]=e,a=Zt(i*r,s),c=Zt(-n*r,s);let l=r-a*t-c*o,u=-a*n-c*i;const f=l<_e,x=u<_e;f&&(l=-l),x&&(u=-u);const _=Et(Math.ceil(an(s)/2))+Le;if(l<_e||l>=_||u<_e||u>=_)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:x,k2:u}}function gt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ut(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Xe(s.lowS,"lowS"),Xe(s.prehash,"prehash"),s.format!==void 0&&gt(s.format),s}class An extends Error{constructor(e=""){super(e)}}const be={Err:An,_tlv:{encode:(r,e)=>{const{Err:s}=be;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=Ke(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?Ke(n.length/2|128):"";return Ke(r)+o+n+e},decode(r,e){const{Err:s}=be;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++],o=!!(n&128);let i=0;if(!o)i=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)i=i<<8|u;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=be;if(r<_e)throw new e("integer: negative integers are not allowed");let s=Ke(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}=be;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 et(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=be,n=V(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{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}=be,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},_e=BigInt(0),Le=BigInt(1),$s=BigInt(2),Ve=BigInt(3),In=BigInt(4);function kn(r,e={}){const s=Sn("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;At(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Us(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f($,m,w){const{x:k,y:O}=m.toAffine(),M=t.toBytes(k);if(Xe(w,"isCompressed"),w){u();const y=!t.isOdd(O);return Se(Bs(y),M)}else return Se(Uint8Array.of(4),M,t.toBytes(O))}function x($){V($,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,k=$.length,O=$[0],M=$.subarray(1);if(k===m&&(O===2||O===3)){const y=t.fromBytes(M);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const b=v(y);let E;try{E=t.sqrt(b)}catch(F){const B=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+B)}u();const A=t.isOdd(E);return(O&1)===1!==A&&(E=t.neg(E)),{x:y,y:E}}else if(k===w&&O===4){const y=t.BYTES,b=t.fromBytes(M.subarray(0,y)),E=t.fromBytes(M.subarray(y,y*2));if(!S(b,E))throw new Error("bad point: is not on curve");return{x:b,y:E}}else throw new Error(`bad point: got length ${k}, expected compressed=${m} or uncompressed=${w}`)}const _=e.toBytes||f,p=e.fromBytes||x;function v($){const m=t.sqr($),w=t.mul(m,$);return t.add(t.add(w,t.mul($,o.a)),o.b)}function S($,m){const w=t.sqr(m),k=v($);return t.eql(w,k)}if(!S(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(o.a,Ve),In),T=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(I,T)))throw new Error("bad curve params: a or b");function H($,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${$}`);return m}function D($){if(!($ instanceof X))throw new Error("Weierstrass Point expected")}function K($){if(!c||!c.basises)throw new Error("no endo");return En($,c.basises,n.ORDER)}const q=Kt(($,m)=>{const{X:w,Y:k,Z:O}=$;if(t.eql(O,t.ONE))return{x:w,y:k};const M=$.is0();m==null&&(m=M?t.ONE:t.inv(O));const y=t.mul(w,m),b=t.mul(k,m),E=t.mul(O,m);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:y,y:b}}),Z=Kt($=>{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(!S(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 W($,m,w,k,O){return w=new X(t.mul(w.X,$),w.Y,w.Z),m=Je(k,m),w=Je(O,w),m.add(w)}const N=class N{constructor(m,w,k){P(this,"X");P(this,"Y");P(this,"Z");this.X=H("x",m),this.Y=H("y",w,!0),this.Z=H("z",k),Object.freeze(this)}static CURVE(){return o}static fromAffine(m){const{x:w,y:k}=m||{};if(!m||!t.isValid(w)||!t.isValid(k))throw new Error("invalid affine point");if(m instanceof N)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(k)?N.ZERO:new N(w,k,t.ONE)}static fromBytes(m){const w=N.fromAffine(p(V(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return N.fromBytes(Ye(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return U.createCache(this,m),w||this.multiply(Ve),this}assertValidity(){Z(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){D(m);const{X:w,Y:k,Z:O}=this,{X:M,Y:y,Z:b}=m,E=t.eql(t.mul(w,b),t.mul(M,O)),A=t.eql(t.mul(k,b),t.mul(y,O));return E&&A}negate(){return new N(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=o,k=t.mul(w,Ve),{X:O,Y:M,Z:y}=this;let b=t.ZERO,E=t.ZERO,A=t.ZERO,R=t.mul(O,O),F=t.mul(M,M),B=t.mul(y,y),L=t.mul(O,M);return L=t.add(L,L),A=t.mul(O,y),A=t.add(A,A),b=t.mul(m,A),E=t.mul(k,B),E=t.add(b,E),b=t.sub(F,E),E=t.add(F,E),E=t.mul(b,E),b=t.mul(L,b),A=t.mul(k,A),B=t.mul(m,B),L=t.sub(R,B),L=t.mul(m,L),L=t.add(L,A),A=t.add(R,R),R=t.add(A,R),R=t.add(R,B),R=t.mul(R,L),E=t.add(E,R),B=t.mul(M,y),B=t.add(B,B),R=t.mul(B,L),b=t.sub(b,R),A=t.mul(B,F),A=t.add(A,A),A=t.add(A,A),new N(b,E,A)}add(m){D(m);const{X:w,Y:k,Z:O}=this,{X:M,Y:y,Z:b}=m;let E=t.ZERO,A=t.ZERO,R=t.ZERO;const F=o.a,B=t.mul(o.b,Ve);let L=t.mul(w,M),G=t.mul(k,y),Y=t.mul(O,b),oe=t.add(w,k),z=t.add(M,y);oe=t.mul(oe,z),z=t.add(L,G),oe=t.sub(oe,z),z=t.add(w,O);let ee=t.add(M,b);return z=t.mul(z,ee),ee=t.add(L,Y),z=t.sub(z,ee),ee=t.add(k,O),E=t.add(y,b),ee=t.mul(ee,E),E=t.add(G,Y),ee=t.sub(ee,E),R=t.mul(F,z),E=t.mul(B,Y),R=t.add(E,R),E=t.sub(G,R),R=t.add(G,R),A=t.mul(E,R),G=t.add(L,L),G=t.add(G,L),Y=t.mul(F,Y),z=t.mul(B,z),G=t.add(G,Y),Y=t.sub(L,Y),Y=t.mul(F,Y),z=t.add(z,Y),L=t.mul(G,z),A=t.add(A,L),L=t.mul(ee,z),E=t.mul(oe,E),E=t.sub(E,L),L=t.mul(oe,G),R=t.mul(ee,R),R=t.add(R,L),new N(E,A,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(N.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let k,O;const M=y=>U.cached(this,y,b=>jt(N,b));if(w){const{k1neg:y,k1:b,k2neg:E,k2:A}=K(m),{p:R,f:F}=M(b),{p:B,f:L}=M(A);O=F.add(L),k=W(w.beta,R,B,y,E)}else{const{p:y,f:b}=M(m);k=y,O=b}return jt(N,[k,O])[0]}multiplyUnsafe(m){const{endo:w}=e,k=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===_e||k.is0())return N.ZERO;if(m===Le)return k;if(U.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:M,k2neg:y,k2:b}=K(m),{p1:E,p2:A}=bn(N,k,M,b);return W(w.beta,E,A,O,y)}else return U.unsafe(k,m)}toAffine(m){return q(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return i===Le?!0:m?m(N,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return i===Le?this:m?m(N,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(m=!0){return Xe(m,"isCompressed"),this.assertValidity(),_(N,this,m)}toHex(m=!0){return Fe(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(N,"BASE",new N(o.Gx,o.Gy,t.ONE)),P(N,"ZERO",new N(t.ZERO,t.ONE,t.ZERO)),P(N,"Fp",t),P(N,"Fn",n);let X=N;const Q=n.BITS,U=new yn(X,e.endo?Math.ceil(Q/2):Q);return X.BASE.precompute(8),X}function Bs(r){return Uint8Array.of(r?2:3)}function Us(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Tn(r,e={}){const{Fn:s}=r,t=e.randomBytes||ms,n=Object.assign(Us(r.Fp,s),{seed:Cs(s.ORDER)});function o(_){try{const p=s.fromBytes(_);return s.isValidNot0(p)}catch{return!1}}function i(_,p){const{publicKey:v,publicKeyUncompressed:S}=n;try{const I=_.length;return p===!0&&I!==v||p===!1&&I!==S?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(n.seed)){return wn(V(_,n.seed,"seed"),s.ORDER)}function c(_,p=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(p)}function l(_){const{secretKey:p,publicKey:v,publicKeyUncompressed:S}=n;if(!bt(_)||"_lengths"in s&&s._lengths||p===v)return;const I=V(_,void 0,"key").length;return I===v||I===S}function u(_,p,v=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const S=s.fromBytes(_);return r.fromBytes(p).multiply(S).toBytes(v)}const f={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},x=vn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,Point:r,utils:f,lengths:n})}function Rn(r,e,s={}){fs(e),At(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||ms,n=s.hmac||((m,w)=>Ms(e,m,w)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:_}=Tn(r,s),p={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},v=a*$s<o.ORDER;function S(m){const w=a>>Le;return m>w}function I(m,w){if(!i.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function T(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function H(m,w){gt(w);const k=_.signature,O=w==="compact"?k:w==="recovered"?k+1:void 0;return V(m,O)}class D{constructor(w,k,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=I("r",w),this.s=I("s",k),O!=null){if(T(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,k=p.format){H(w,k);let O;if(k==="der"){const{r:E,s:A}=be.toSig(V(w));return new D(E,A)}k==="recovered"&&(O=w[0],k="compact",w=w.subarray(1));const M=_.signature/2,y=w.subarray(0,M),b=w.subarray(M,M*2);return new D(i.fromBytes(y),i.fromBytes(b),O)}static fromHex(w,k){return this.fromBytes(Ye(w),k)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new D(this.r,this.s,w)}recoverPublicKey(w){const{r:k,s:O}=this,M=this.assertRecovery(),y=M===2||M===3?k+a:k;if(!o.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const b=o.toBytes(y),E=r.fromBytes(Se(Bs((M&1)===0),b)),A=i.inv(y),R=q(V(w,void 0,"msgHash")),F=i.create(-R*A),B=i.create(O*A),L=r.BASE.multiplyUnsafe(F).add(E.multiplyUnsafe(B));if(L.is0())throw new Error("invalid recovery: point at infinify");return L.assertValidity(),L}hasHighS(){return S(this.s)}toBytes(w=p.format){if(gt(w),w==="der")return Ye(be.hexFromSig(this));const{r:k,s:O}=this,M=i.toBytes(k),y=i.toBytes(O);return w==="recovered"?(T(),Se(Uint8Array.of(this.assertRecovery()),M,y)):Se(M,y)}toHex(w){return Fe(this.toBytes(w))}}const K=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const k=et(w),O=w.length*8-c;return O>0?k>>BigInt(O):k},q=s.bits2int_modN||function(w){return i.create(K(w))},Z=Et(c);function W(m){return on("num < 2^"+c,m,_e,Z),i.toBytes(m)}function X(m,w){return V(m,void 0,"message"),w?V(e(m),void 0,"prehashed message"):m}function Q(m,w,k){const{lowS:O,prehash:M,extraEntropy:y}=ut(k,p);m=X(m,M);const b=q(m),E=i.fromBytes(w);if(!i.isValidNot0(E))throw new Error("invalid private key");const A=[W(E),W(b)];if(y!=null&&y!==!1){const L=y===!0?t(_.secretKey):y;A.push(V(L,void 0,"extraEntropy"))}const R=Se(...A),F=b;function B(L){const G=K(L);if(!i.isValidNot0(G))return;const Y=i.inv(G),oe=r.BASE.multiply(G).toAffine(),z=i.create(oe.x);if(z===_e)return;const ee=i.create(Y*i.create(F+z*E));if(ee===_e)return;let Ot=(oe.x===z?0:2)|Number(oe.y&Le),Pt=ee;return O&&S(ee)&&(Pt=i.neg(ee),Ot^=1),new D(z,Pt,v?void 0:Ot)}return{seed:R,k2sig:B}}function U(m,w,k={}){const{seed:O,k2sig:M}=Q(m,w,k);return cn(e.outputLen,i.BYTES,n)(O,M).toBytes(k.format)}function N(m,w,k,O={}){const{lowS:M,prehash:y,format:b}=ut(O,p);if(k=V(k,void 0,"publicKey"),w=X(w,y),!bt(m)){const E=m instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}H(m,b);try{const E=D.fromBytes(m,b),A=r.fromBytes(k);if(M&&E.hasHighS())return!1;const{r:R,s:F}=E,B=q(w),L=i.inv(F),G=i.create(B*L),Y=i.create(R*L),oe=r.BASE.multiplyUnsafe(G).add(A.multiplyUnsafe(Y));return oe.is0()?!1:i.create(oe.x)===R}catch{return!1}}function $(m,w,k={}){const{prehash:O}=ut(k,p);return w=X(w,O),D.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:x,lengths:_,Point:r,sign:U,verify:N,recoverPublicKey:$,Signature:D,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},On={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Qt=BigInt(2);function Pn(r){const e=kt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ae(u,s,e)*u%e,x=ae(f,s,e)*u%e,_=ae(x,Qt,e)*l%e,p=ae(_,n,e)*_%e,v=ae(p,o,e)*p%e,S=ae(v,a,e)*v%e,I=ae(S,c,e)*S%e,T=ae(I,a,e)*v%e,H=ae(T,s,e)*u%e,D=ae(H,i,e)*p%e,K=ae(D,t,e)*l%e,q=ae(K,Qt,e);if(!mt.eql(mt.sqr(q),r))throw new Error("Cannot find square root");return q}const mt=tt(kt.p,{sqrt:Pn}),Cn=kn(kt,{Fp:mt,endo:On}),Nn=Rn(Cn,sn),Ln=BigInt(0),Be=BigInt(1),Dn=BigInt(2),Mn=BigInt(7),$n=BigInt(256),Bn=BigInt(113),Hs=[],Fs=[],Ws=[];for(let r=0,e=Be,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Hs.push(2*(5*t+s)),Fs.push((r+1)*(r+2)/2%64);let n=Ln;for(let o=0;o<7;o++)e=(e<<Be^(e>>Mn)*Bn)%$n,e&Dn&&(n^=Be<<(Be<<BigInt(o))-Be);Ws.push(n)}const Gs=jr(Ws,!0),Un=Gs[0],Hn=Gs[1],es=(r,e,s)=>s>32?Jr(r,e,s):Yr(r,e,s),ts=(r,e,s)=>s>32?Zr(r,e,s):Xr(r,e,s);function Fn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],u=s[c+1],f=es(l,u,1)^s[a],x=ts(l,u,1)^s[a+1];for(let _=0;_<50;_+=10)r[i+_]^=f,r[i+_+1]^=x}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Fs[i],c=es(n,o,a),l=ts(n,o,a),u=Hs[i];n=r[u],o=r[u+1],r[u]=c,r[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Un[t],r[1]^=Hn[t]}Me(s)}class Tt{constructor(e,s,t,n=!1,o=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,me(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Br(this.state)}clone(){return this._cloneInto()}keccak(){Wt(this.state32),Fn(this.state32,this.rounds),Wt(this.state32),this.posOut=0,this.pos=0}update(e){De(this),V(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];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){De(this,!1),V(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return me(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(_s(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,Me(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new Tt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Wn=(r,e,s,t={})=>gs(()=>new Tt(e,r,s),t),ss=Wn(1,136,32),Gn=60;class qn{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=rt.createRemoteJWKSet(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+Gn<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:o}=await rt.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{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 rt.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
6
+ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=ss(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Kn(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],x=f>=27?f-27:f,v=new Nn.Signature(rs(l),rs(u)).addRecoveryBit(x).recoverPublicKey(i).toBytes(!1).slice(1),S=ss(v);return"0x"+Fe(S.slice(12))}}function Kn(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 rs(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const Vn=3e4,zn=1e3;class jn{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,zn*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??Vn);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 o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Yn=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ee{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=Ee.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.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:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const i=await Ee.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)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:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Ee.generateRandom16Hex(),l=Ee.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",f=`${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(f,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),D(),t(new Error("Authentication timeout"))},5*60*1e3),p=10,v=30;let S=0,I=null;const T=()=>{clearInterval(H),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),I=setTimeout(()=>{D(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},H=setInterval(()=>{S++;try{x.closed&&(S<=p?T():(D(),t(new Error("로그인이 취소되었습니다"))))}catch{T()}},1e3),D=()=>{clearTimeout(_),clearInterval(H),I&&clearTimeout(I),window.removeEventListener("message",K)},K=q=>{if(q.origin!==e.expectedOrigin)return;if(!Yn.has(q.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",q.origin),D(),t(new Error("Unauthorized OAuth origin"));return}D();const Z=typeof q.data.status=="string",W=Z?q.data.data??{}:q.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:Z?"wrapped":"flat",status:Z?q.data.status:"(flat)"});const X=(W==null?void 0:W.state)??q.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(Z&&q.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",W==null?void 0:W.error),t(new Error((W==null?void 0:W.error)||"Authentication failed"));return}if(!Z&&(W!=null&&W.error)){d.error("[CROSSx] OAuth 실패:",W.error),t(new Error(W.error||"Authentication failed"));return}const Q=W==null?void 0:W.idToken,U=W==null?void 0:W.accessToken,N=U??Q,$=(W==null?void 0:W.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!Q,hasEmail:!!$}),!N){d.error("[CROSSx] 토큰을 찾을 수 없음:",q.data),t(new Error("Token not found in response"));return}const m={token:N,email:$},w=k=>{Ee.verifyIdTokenNonce(k,l).then(()=>s(m)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?w(U):Q?w(Q):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):Q?w(Q):t(new Error("Token not found in response"))};window.addEventListener("message",K)})}}const Ue="crossx_wallet_data",Re="crossx_mock_pin_hash";class Xn{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(Ue)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Ue);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(Ue,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Re,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Ue);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()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,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(Re);return s&&s!==e?!1:(s||await this.storage.set(Re,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(h.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Re);if(n&&t&&n!==t)throw new g(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Re,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new g(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 g(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(Ue,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Re,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 Ae{constructor(e,s,t,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(Ht))return e;const s=!e||this.tokenStore.isExpiringSoon(Ht);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(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,f;const o=await this.ensureValidToken(),i=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:i,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const p=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:p,url:i,method:e});const v=Ae.mapGatewayError(_.code,_.data);if(v===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 g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(v===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(h.USER_NOT_FOUND,Ae.getGatewayErrorMessage(_.code,p));const S=v===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:v,I=S===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Ae.getGatewayErrorMessage(_.code,p),T=_.data,H=v===h.PIN_LOCKED?Ae.extractLockDetails(T):T??void 0;throw new g(S,I,H)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:i,method:e}),_.data??_}return _}catch(x){if(x instanceof g)throw x;const _=((l=x.response)==null?void 0:l.status)??x.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=x.response)!=null&&u.data){const p=x.response.data,v=p.message||p.data||"API 요청에 실패했습니다",S=p.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:S,message:v,url:i,method:e,status:(f=x.response)==null?void 0:f.status}),new g(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${S}): ${v}`)}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 g(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.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 g(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new g(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 g(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);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,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).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 g(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const o=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new g(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:o,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new g(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 g(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 o=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof o=="number"&&(t.remainingAttempts=o);const i=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof i=="number"&&(t.maxAttempts=i),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-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 Ae.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-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class He{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=He.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?gr:xr;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 g(He.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=He.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new g(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Qe).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 ns="__crossx-confirm-style",J="__crossx-confirm-overlay",Jn={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 os(r,e){const s=Jn[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 Zn=`
7
7
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
8
8
 
9
- #${Z} {
9
+ #${J} {
10
10
  position: fixed;
11
11
  inset: 0;
12
12
  z-index: 2147483647;
@@ -1205,9 +1205,14 @@ button.__crossx-connect-other-block:active {
1205
1205
  overscroll-behavior: contain;
1206
1206
  touch-action: pan-y;
1207
1207
  scrollbar-width: thin;
1208
+ scrollbar-color: var(--cx-divider) transparent;
1208
1209
  }
1209
1210
  .__crossx-wallet-list::-webkit-scrollbar {
1210
1211
  width: 4px;
1212
+ background: transparent;
1213
+ }
1214
+ .__crossx-wallet-list::-webkit-scrollbar-track {
1215
+ background: transparent;
1211
1216
  }
1212
1217
  .__crossx-wallet-list::-webkit-scrollbar-thumb {
1213
1218
  background: var(--cx-divider);
@@ -1216,12 +1221,11 @@ button.__crossx-connect-other-block:active {
1216
1221
  .__crossx-wallet-item {
1217
1222
  display: flex;
1218
1223
  align-items: center;
1219
- justify-content: space-between;
1220
- gap: 8px;
1224
+ gap: 12px;
1221
1225
  padding: 16px;
1222
1226
  background: var(--cx-pill-bg);
1223
1227
  border: 1px solid var(--cx-border);
1224
- border-radius: 8px;
1228
+ border-radius: 12px;
1225
1229
  cursor: pointer;
1226
1230
  appearance: none;
1227
1231
  -webkit-appearance: none;
@@ -1232,6 +1236,9 @@ button.__crossx-connect-other-block:active {
1232
1236
  text-align: left;
1233
1237
  font-family: 'Sora', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
1234
1238
  }
1239
+ .__crossx-wallet-item--selected {
1240
+ border-color: var(--cx-primary);
1241
+ }
1235
1242
  .__crossx-wallet-item:hover,
1236
1243
  .__crossx-wallet-item:focus,
1237
1244
  .__crossx-wallet-item:active {
@@ -1242,43 +1249,81 @@ button.__crossx-connect-other-block:active {
1242
1249
  transform: none !important;
1243
1250
  background: var(--cx-pill-bg) !important;
1244
1251
  }
1252
+ .__crossx-wallet-avatar {
1253
+ width: 32px;
1254
+ height: 32px;
1255
+ flex-shrink: 0;
1256
+ border-radius: 50%;
1257
+ overflow: hidden;
1258
+ display: flex;
1259
+ align-items: center;
1260
+ justify-content: center;
1261
+ background: var(--cx-surface-subtle);
1262
+ }
1263
+ .__crossx-wallet-avatar-img {
1264
+ width: 28px;
1265
+ height: 28px;
1266
+ object-fit: cover;
1267
+ display: block;
1268
+ }
1269
+ .__crossx-wallet-avatar-fallback {
1270
+ width: 100%;
1271
+ height: 100%;
1272
+ display: none;
1273
+ align-items: center;
1274
+ justify-content: center;
1275
+ }
1276
+ .__crossx-wallet-avatar-fallback svg {
1277
+ width: 100%;
1278
+ height: 100%;
1279
+ display: block;
1280
+ }
1245
1281
  .__crossx-wallet-info {
1246
1282
  display: flex;
1247
1283
  flex-direction: column;
1248
1284
  align-items: flex-start;
1249
- gap: 2px;
1285
+ gap: 4px;
1250
1286
  min-width: 0;
1251
1287
  flex: 1;
1252
1288
  }
1253
1289
  .__crossx-wallet-idx {
1254
- font-size: 16px;
1290
+ font-size: 14px;
1255
1291
  font-weight: 600;
1256
1292
  line-height: 1.3;
1257
1293
  color: var(--cx-value);
1258
1294
  white-space: nowrap;
1295
+ overflow: hidden;
1296
+ text-overflow: ellipsis;
1297
+ max-width: 100%;
1259
1298
  }
1260
1299
  .__crossx-wallet-addr {
1261
- font-size: 13px;
1262
- font-weight: 500;
1300
+ font-size: 14px;
1301
+ font-weight: 400;
1263
1302
  line-height: 1.3;
1264
1303
  color: var(--cx-label);
1265
1304
  white-space: nowrap;
1266
1305
  }
1267
1306
  .__crossx-wallet-selected {
1268
- font-size: 14px;
1307
+ font-size: 13px;
1269
1308
  font-weight: 600;
1270
- line-height: 1.4;
1309
+ line-height: 1.3;
1271
1310
  color: #ffffff;
1272
1311
  background: var(--cx-primary);
1273
- border-radius: 12px;
1274
- height: 28px;
1275
- padding: 0 12px;
1312
+ border-radius: 4px;
1313
+ padding: 4px 8px;
1276
1314
  margin-left: auto;
1277
1315
  flex-shrink: 0;
1278
1316
  white-space: nowrap;
1279
1317
  display: flex;
1280
1318
  align-items: center;
1281
1319
  }
1320
+ .__crossx-wallet-check {
1321
+ display: none;
1322
+ flex-shrink: 0;
1323
+ margin-left: auto;
1324
+ width: 24px;
1325
+ height: 24px;
1326
+ }
1282
1327
  .__crossx-wallet-add {
1283
1328
  display: flex;
1284
1329
  align-items: center;
@@ -1327,7 +1372,7 @@ button.__crossx-connect-other-block:active {
1327
1372
  }
1328
1373
  /* ── Mobile bottom sheet ───────────────────────────────────── */
1329
1374
  @media (max-width: 480px) {
1330
- #${Z} { align-items: flex-end; }
1375
+ #${J} { align-items: flex-end; }
1331
1376
  .__crossx-safe-area-fill {
1332
1377
  display: block;
1333
1378
  position: fixed;
@@ -1383,6 +1428,8 @@ button.__crossx-connect-other-block:active {
1383
1428
  max-height: 203px;
1384
1429
  }
1385
1430
  .__crossx-card--wallet-selector .__crossx-wallet-add { flex-shrink: 0; }
1431
+ .__crossx-wallet-selected { display: none !important; }
1432
+ .__crossx-wallet-check { display: flex !important; }
1386
1433
  .__crossx-card--send-tx,
1387
1434
  .__crossx-card--sign-tx,
1388
1435
  .__crossx-card--sign-msg,
@@ -1535,7 +1582,7 @@ button.__crossx-connect-other-block:active {
1535
1582
 
1536
1583
  /* ── Landscape for signing/transaction modals ──────────── */
1537
1584
  @media (orientation: landscape) and (max-height: 500px) {
1538
- #${Z} { align-items: center !important; overflow: hidden; }
1585
+ #${J} { align-items: center !important; overflow: hidden; }
1539
1586
  .__crossx-card--send-tx,
1540
1587
  .__crossx-card--sign-tx,
1541
1588
  .__crossx-card--sign-msg,
@@ -2030,58 +2077,54 @@ button.__crossx-connect-other-block:active {
2030
2077
  color: var(--cx-title);
2031
2078
  margin: 0;
2032
2079
  }
2033
- `;function le(){let r=document.getElementById(rs);r||(r=document.createElement("style"),r.id=rs,document.head.appendChild(r)),r.textContent=On}function Pn(){const r=`#${Z}`,e=t=>{var n,o;(o=(n=t.target)==null?void 0:n.closest)!=null&&o.call(n,r)&&t.stopImmediatePropagation()},s=t=>{var n,o;(o=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&o.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 de(r){const e=r.querySelector(".__crossx-card");if(e){const i=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(i){const a=i[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=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(o,s);r.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])r.addEventListener(o,s);r.addEventListener("touchmove",o=>{o.stopPropagation();let i=o.target;for(;i&&i!==r;){const a=window.getComputedStyle(i);if((a.overflowY==="auto"||a.overflowY==="scroll")&&i.scrollHeight>i.clientHeight)return;i=i.parentElement}o.preventDefault()},{passive:!1});const t=Pn(),n=r.remove.bind(r);r.remove=()=>{t(),n()},document.body.appendChild(r)}const Cn=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Oe(){if(Cn()){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 re(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function Hs(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=gt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const os={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 Ws(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&os[e]?os[e]:r}function gt(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function dt(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 Nn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function Ln(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=Nn(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${gt(l,i)} ${o}`,maxFeeGwei:dt(t),maxPriorityFeeGwei:n?dt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${gt(l,i)} ${o}`,gasPriceGwei:dt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Gs(r){const e=Ln(r);if(!e)return Y("Estimated fee","<span>—</span>");let s=Y("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=Y("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=Y("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=Y("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=Y("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const me=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2080
+ `;function ce(){let r=document.getElementById(ns);r||(r=document.createElement("style"),r.id=ns,document.head.appendChild(r)),r.textContent=Zn}function Qn(){const r=`#${J}`,e=t=>{var n,o;(o=(n=t.target)==null?void 0:n.closest)!=null&&o.call(n,r)&&t.stopImmediatePropagation()},s=t=>{var n,o;(o=(n=t.relatedTarget)==null?void 0:n.closest)!=null&&o.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 le(r){const e=r.querySelector(".__crossx-card");if(e){const i=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(i){const a=i[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=o=>o.stopPropagation();for(const o of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(o,s);r.setAttribute("data-vaul-no-drag","");for(const o of["touchstart","touchend"])r.addEventListener(o,s);r.addEventListener("touchmove",o=>{o.stopPropagation();let i=o.target;for(;i&&i!==r;){const a=window.getComputedStyle(i);if((a.overflowY==="auto"||a.overflowY==="scroll")&&i.scrollHeight>i.clientHeight)return;i=i.parentElement}o.preventDefault()},{passive:!1});const t=Qn(),n=r.remove.bind(r);r.remove=()=>{t(),n()},document.body.appendChild(r)}const eo=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Oe(){if(eo()){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 se(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function qs(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=wt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const is={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 Ks(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&is[e]?is[e]:r}function wt(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function ht(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 to(r){try{return BigInt(r).toLocaleString()}catch{return r}}function so(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=to(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${wt(l,i)} ${o}`,maxFeeGwei:ht(t),maxPriorityFeeGwei:n?ht(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${wt(l,i)} ${o}`,gasPriceGwei:ht(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Vs(r){const e=so(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 ge=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
2034
2081
  <rect x="9" y="9" width="13" height="13" rx="2"/>
2035
2082
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
2036
- </svg>`,oe=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
2083
+ </svg>`,ne=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
2037
2084
  <line x1="18" y1="6" x2="6" y2="18"/>
2038
2085
  <line x1="6" y1="6" x2="18" y2="18"/>
2039
- </svg>`,Dn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2086
+ </svg>`,ro=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2040
2087
  <circle cx="20" cy="20" r="20" fill="#00D5AA"/>
2041
2088
  <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"/>
2042
- </svg>`,$n='<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>',Mn='<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>',Bn='<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>',Un={[Pe.MetaMask]:$n,[Pe.Binance]:Mn,[Pe.CROSSx]:Bn},Tt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
2043
- <rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
2044
- <path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
2045
- <rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
2046
- </svg>`,Fn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2089
+ </svg>`,no='<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>',oo='<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>',io='<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>',ao={[Ce.MetaMask]:no,[Ce.Binance]:oo,[Ce.CROSSx]:io},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"/>',Rt=`<svg width="20" height="20" viewBox="0 0 32 32" fill="currentColor" xmlns="http://www.w3.org/2000/svg">${zs}</svg>`,co=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2047
2090
  <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)"/>
2048
- </svg>`,Hn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2091
+ </svg>`,lo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
2049
2092
  <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
2050
2093
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
2051
2094
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
2052
- </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 Y(r,e){return`
2095
+ </svg>`;function ie(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`
2053
2096
  <div class="__crossx-row">
2054
2097
  <span class="__crossx-row-label">${r}</span>
2055
2098
  <div class="__crossx-row-value">${e}</div>
2056
- </div>`}function Wn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=tt(r.dappName),i=r.to?`<span class="__crossx-addr-text">${re(r.to)}</span>
2057
- <button class="__crossx-copy-btn" data-copy="${L(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",a=Gs(r),c=Hs(r.value,t,n),l=c?Y("Value",`<span>${c}</span>`):"",u=r.data??"0x",f=document.createElement("div");return f.id=Z,f.innerHTML=`
2058
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2099
+ </div>`}function uo(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=st(r.dappName),i=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
2100
+ <button class="__crossx-copy-btn" data-copy="${C(r.to)}" title="Copy address">${ge}</button>`:"<span>—</span>",a=Vs(r),c=qs(r.value,t,n),l=c?j("Value",`<span>${c}</span>`):"",u=r.data??"0x",f=document.createElement("div");return f.id=J,f.innerHTML=`
2101
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2059
2102
  <div class="__crossx-header">
2060
2103
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
2061
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2104
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2062
2105
  </div>
2063
2106
  <hr class="__crossx-divider">
2064
2107
  <div class="__crossx-body">
2065
2108
  <div class="__crossx-body-cols">
2066
2109
  <div class="__crossx-col-left">
2067
2110
  <p class="__crossx-sig-subtitle">
2068
- <span class="__crossx-sig-origin">${L(o)} </span>is requesting a Signature
2111
+ <span class="__crossx-sig-origin">${C(o)} </span>is requesting a Signature
2069
2112
  </p>
2070
2113
  <div class="__crossx-addr-pill">
2071
- ${Tt}
2072
- <span class="__crossx-addr-pill-text">${re(r.from)}</span>
2114
+ ${Rt}
2115
+ <span class="__crossx-addr-pill-text">${se(r.from)}</span>
2073
2116
  </div>
2074
2117
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
2075
2118
  </div>
2076
2119
  <hr class="__crossx-divider __crossx-divider--cols">
2077
2120
  <div class="__crossx-col-right-sign">
2078
2121
  <div class="__crossx-rows">
2079
- ${Y("To",i)}
2080
- ${Y("Network",`<span>${Ws(r.chainId)}</span>`)}
2122
+ ${j("To",i)}
2123
+ ${j("Network",`<span>${Ks(r.chainId)}</span>`)}
2081
2124
  ${l}
2082
2125
  ${a}
2083
2126
  </div>
2084
- <pre class="__crossx-raw-tx">${L(u)}</pre>
2127
+ <pre class="__crossx-raw-tx">${C(u)}</pre>
2085
2128
  </div>
2086
2129
  </div>
2087
2130
  <div class="__crossx-btn-row">
@@ -2090,43 +2133,43 @@ button.__crossx-connect-other-block:active {
2090
2133
  </div>
2091
2134
  </div>
2092
2135
  </div>
2093
- `,f}function Gn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=tt(r.dappName),i=r.to?`<span class="__crossx-addr-text">${re(r.to)}</span>
2094
- <button class="__crossx-copy-btn" data-copy="${L(r.to)}" title="Copy address">${me}</button>`:"<span>—</span>",a=Gs(r),l=Hs(r.value,t,n)??"—",u=document.createElement("div");return u.id=Z,u.innerHTML=`
2095
- <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2136
+ `,f}function ho(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=st(r.dappName),i=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
2137
+ <button class="__crossx-copy-btn" data-copy="${C(r.to)}" title="Copy address">${ge}</button>`:"<span>—</span>",a=Vs(r),l=qs(r.value,t,n)??"—",u=document.createElement("div");return u.id=J,u.innerHTML=`
2138
+ <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2096
2139
  <div class="__crossx-header">
2097
2140
  <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
2098
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2141
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2099
2142
  </div>
2100
2143
  <hr class="__crossx-divider">
2101
2144
  <div class="__crossx-body">
2102
2145
  <p class="__crossx-tx-subtitle">
2103
- <span class="__crossx-sig-origin">${L(o)}</span> wants your permission to approve the following transaction.
2146
+ <span class="__crossx-sig-origin">${C(o)}</span> wants your permission to approve the following transaction.
2104
2147
  </p>
2105
2148
  <div class="__crossx-body-cols">
2106
2149
  <div class="__crossx-rows">
2107
- ${Y("To",i)}
2108
- ${Y("Network",`<span>${Ws(r.chainId)}</span>`)}
2150
+ ${j("To",i)}
2151
+ ${j("Network",`<span>${Ks(r.chainId)}</span>`)}
2109
2152
  ${a}
2110
2153
  </div>
2111
2154
  <div class="__crossx-pill">
2112
- <span class="__crossx-pill-from">${re(r.from)}</span>
2155
+ <span class="__crossx-pill-from">${se(r.from)}</span>
2113
2156
  <span class="__crossx-pill-amount">${l}</span>
2114
2157
  </div>
2115
2158
  </div>
2116
2159
  <button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
2117
2160
  </div>
2118
2161
  </div>
2119
- `,u}function tt(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function L(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function qn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Kn(r){if(typeof r=="string")return L(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return L(JSON.stringify(r))}catch{return String(r)}}function zn(r,e){const s=Y("From",`<span class="__crossx-addr-text">${re(r.from)}</span>
2120
- <button class="__crossx-copy-btn" data-copy="${L(r.from)}" title="Copy address">${me}</button>`),t=r.to?Y("To",`<span class="__crossx-addr-text">${re(r.to)}</span>
2121
- <button class="__crossx-copy-btn" data-copy="${L(r.to)}" title="Copy address">${me}</button>`):"",n=r.amount?Y("Transfer",`<span>${L(r.amount)}</span>`):"",o=r.fees?Y("Tx Fee",`<span>${L(r.fees)}</span>`):"",i=r.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${re(r.txHash)}</span>
2122
- <button class="__crossx-copy-btn" data-copy="${L(r.txHash)}" title="Copy hash">${me}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
2162
+ `,u}function st(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function C(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function po(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function fo(r){if(typeof r=="string")return C(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return C(JSON.stringify(r))}catch{return String(r)}}function _o(r,e){const s=j("From",`<span class="__crossx-addr-text">${se(r.from)}</span>
2163
+ <button class="__crossx-copy-btn" data-copy="${C(r.from)}" title="Copy address">${ge}</button>`),t=r.to?j("To",`<span class="__crossx-addr-text">${se(r.to)}</span>
2164
+ <button class="__crossx-copy-btn" data-copy="${C(r.to)}" title="Copy address">${ge}</button>`):"",n=r.amount?j("Transfer",`<span>${C(r.amount)}</span>`):"",o=r.fees?j("Tx Fee",`<span>${C(r.fees)}</span>`):"",i=r.txHash?j("Tx Hash",`<span class="__crossx-addr-text">${se(r.txHash)}</span>
2165
+ <button class="__crossx-copy-btn" data-copy="${C(r.txHash)}" title="Copy hash">${ge}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
2123
2166
  <span class="__crossx-total-label">Total<br>(including fees)</span>
2124
- <span class="__crossx-total-amount">${L(r.total)}</span>
2125
- </div>`:"",c=document.createElement("div");return c.id=Z,c.innerHTML=`
2126
- <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2167
+ <span class="__crossx-total-amount">${C(r.total)}</span>
2168
+ </div>`:"",c=document.createElement("div");return c.id=J,c.innerHTML=`
2169
+ <div class="__crossx-card __crossx-card--migration" style="${ie(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2127
2170
  <div class="__crossx-header">
2128
2171
  <p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
2129
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2172
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2130
2173
  </div>
2131
2174
  <hr class="__crossx-divider">
2132
2175
  <div class="__crossx-body">
@@ -2141,8 +2184,8 @@ button.__crossx-connect-other-block:active {
2141
2184
  <button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
2142
2185
  </div>
2143
2186
  </div>
2144
- `,c}function Vn(r,e){const s=document.createElement("div");return s.id=Z,s.innerHTML=`
2145
- <div class="__crossx-card __crossx-card--migration" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2187
+ `,c}function xo(r,e){const s=document.createElement("div");return s.id=J,s.innerHTML=`
2188
+ <div class="__crossx-card __crossx-card--migration" style="${ie(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2146
2189
  <div class="__crossx-header">
2147
2190
  <p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
2148
2191
  </div>
@@ -2154,38 +2197,38 @@ button.__crossx-connect-other-block:active {
2154
2197
  </div>
2155
2198
  </div>
2156
2199
  </div>
2157
- `,s}function jn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const b=n?Hn:t?"":Fn,E=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";b?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${b}<span>${E}</span>`):o.textContent=E}if(i&&!r.querySelector("#__crossx-close-btn")){const b=document.createElement("button");b.className="__crossx-close",b.id="__crossx-close-btn",b.setAttribute("aria-label","Close"),b.innerHTML=oe,i.appendChild(b)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?Y("From",`<span class="__crossx-addr-text">${re(e.from)}</span>
2158
- <button class="__crossx-copy-btn" data-copy="${L(e.from)}" title="Copy address">${me}</button>`):"",l=e.to?Y("To",`<span class="__crossx-addr-text">${re(e.to)}</span>
2159
- <button class="__crossx-copy-btn" data-copy="${L(e.to)}" title="Copy address">${me}</button>`):"",u=e.amount?Y("Transfer",`<span>${L(e.amount)}</span>`):"",f=e.fees?Y("Tx Fee",`<span>${L(e.fees)}</span>`):"",_=e.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${re(e.txHash)}</span>
2160
- <button class="__crossx-copy-btn" data-copy="${L(e.txHash)}" title="Copy hash">${me}</button>`):"",p=e.total?`<div class="__crossx-total-pill">
2200
+ `,s}function go(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const p=n?lo:t?"":co,v=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";p?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${p}<span>${v}</span>`):o.textContent=v}if(i&&!r.querySelector("#__crossx-close-btn")){const p=document.createElement("button");p.className="__crossx-close",p.id="__crossx-close-btn",p.setAttribute("aria-label","Close"),p.innerHTML=ne,i.appendChild(p)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?j("From",`<span class="__crossx-addr-text">${se(e.from)}</span>
2201
+ <button class="__crossx-copy-btn" data-copy="${C(e.from)}" title="Copy address">${ge}</button>`):"",l=e.to?j("To",`<span class="__crossx-addr-text">${se(e.to)}</span>
2202
+ <button class="__crossx-copy-btn" data-copy="${C(e.to)}" title="Copy address">${ge}</button>`):"",u=e.amount?j("Transfer",`<span>${C(e.amount)}</span>`):"",f=e.fees?j("Tx Fee",`<span>${C(e.fees)}</span>`):"",x=e.txHash?j("Tx Hash",`<span class="__crossx-addr-text">${se(e.txHash)}</span>
2203
+ <button class="__crossx-copy-btn" data-copy="${C(e.txHash)}" title="Copy hash">${ge}</button>`):"",_=e.total?`<div class="__crossx-total-pill">
2161
2204
  <span class="__crossx-total-label">Total<br>(including fees)</span>
2162
- <span class="__crossx-total-amount">${L(e.total)}</span>
2205
+ <span class="__crossx-total-amount">${C(e.total)}</span>
2163
2206
  </div>`:"";a.innerHTML=`
2164
2207
  <div class="__crossx-rows">
2165
2208
  ${c}
2166
2209
  ${l}
2167
2210
  ${u}
2168
2211
  ${f}
2169
- ${_}
2212
+ ${x}
2170
2213
  </div>
2171
- ${p}
2214
+ ${_}
2172
2215
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
2173
- `,a.querySelectorAll(".__crossx-copy-btn").forEach(b=>{b.addEventListener("click",E=>{var A;E.stopPropagation();const S=b.dataset.copy;S&&((A=navigator.clipboard)==null||A.writeText(S).catch(()=>{}))})})}function Yn(r,e){const s=e,t=tt(r.dappName),n=L(r.message),o=document.createElement("div");return o.id=Z,o.innerHTML=`
2174
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2216
+ `,a.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",v=>{var I;v.stopPropagation();const S=p.dataset.copy;S&&((I=navigator.clipboard)==null||I.writeText(S).catch(()=>{}))})})}function mo(r,e){const s=e,t=st(r.dappName),n=C(r.message),o=document.createElement("div");return o.id=J,o.innerHTML=`
2217
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2175
2218
  <div class="__crossx-header">
2176
2219
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
2177
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2220
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2178
2221
  </div>
2179
2222
  <hr class="__crossx-divider">
2180
2223
  <div class="__crossx-body">
2181
2224
  <div class="__crossx-body-cols">
2182
2225
  <div class="__crossx-col-left">
2183
2226
  <p class="__crossx-sig-subtitle">
2184
- <span class="__crossx-sig-origin">${L(t)} </span>is requesting a Signature
2227
+ <span class="__crossx-sig-origin">${C(t)} </span>is requesting a Signature
2185
2228
  </p>
2186
2229
  <div class="__crossx-addr-pill">
2187
- ${Tt}
2188
- <span class="__crossx-addr-pill-text">${re(r.from)}</span>
2230
+ ${Rt}
2231
+ <span class="__crossx-addr-pill-text">${se(r.from)}</span>
2189
2232
  </div>
2190
2233
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
2191
2234
  </div>
@@ -2198,31 +2241,31 @@ button.__crossx-connect-other-block:active {
2198
2241
  </div>
2199
2242
  </div>
2200
2243
  </div>
2201
- `,o}function Xn(r,e){const s=e,t=tt(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 o=n.primaryType??"—",i=n.message??{};let a=`
2244
+ `,o}function wo(r,e){const s=e,t=st(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 o=n.primaryType??"—",i=n.message??{};let a=`
2202
2245
  <div class="__crossx-td-row">
2203
2246
  <span class="__crossx-td-label">Primary Type</span>
2204
- <span class="__crossx-td-value">${L(o)}</span>
2205
- </div>`;for(const[l,u]of Object.entries(i)){const f=Kn(u),p=qn(u)?`<span class="__crossx-addr-text">${re(u)}</span>
2206
- <button class="__crossx-copy-btn" data-copy="${L(String(u))}" title="Copy">${me}</button>`:`<span>${f}</span>`;a+=`
2247
+ <span class="__crossx-td-value">${C(o)}</span>
2248
+ </div>`;for(const[l,u]of Object.entries(i)){const f=fo(u),_=po(u)?`<span class="__crossx-addr-text">${se(u)}</span>
2249
+ <button class="__crossx-copy-btn" data-copy="${C(String(u))}" title="Copy">${ge}</button>`:`<span>${f}</span>`;a+=`
2207
2250
  <div class="__crossx-td-row">
2208
- <span class="__crossx-td-label">${L(l)}</span>
2209
- <div class="__crossx-td-value">${p}</div>
2210
- </div>`}const c=document.createElement("div");return c.id=Z,c.innerHTML=`
2211
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2251
+ <span class="__crossx-td-label">${C(l)}</span>
2252
+ <div class="__crossx-td-value">${_}</div>
2253
+ </div>`}const c=document.createElement("div");return c.id=J,c.innerHTML=`
2254
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2212
2255
  <div class="__crossx-header">
2213
2256
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
2214
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2257
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2215
2258
  </div>
2216
2259
  <hr class="__crossx-divider">
2217
2260
  <div class="__crossx-body">
2218
2261
  <div class="__crossx-body-cols">
2219
2262
  <div class="__crossx-col-left">
2220
2263
  <p class="__crossx-sig-subtitle">
2221
- <span class="__crossx-sig-origin">${L(t)} </span>is requesting a Signature
2264
+ <span class="__crossx-sig-origin">${C(t)} </span>is requesting a Signature
2222
2265
  </p>
2223
2266
  <div class="__crossx-addr-pill">
2224
- ${Tt}
2225
- <span class="__crossx-addr-pill-text">${re(r.from)}</span>
2267
+ ${Rt}
2268
+ <span class="__crossx-addr-pill-text">${se(r.from)}</span>
2226
2269
  </div>
2227
2270
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
2228
2271
  </div>
@@ -2235,19 +2278,19 @@ button.__crossx-connect-other-block:active {
2235
2278
  </div>
2236
2279
  </div>
2237
2280
  </div>
2238
- `,c}const Jn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2281
+ `,c}const yo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
2239
2282
  <line x1="12" y1="5" x2="12" y2="19"/>
2240
2283
  <line x1="5" y1="12" x2="19" y2="12"/>
2241
- </svg>`;function Zn(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${L(i.address)}">
2242
- <span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${i.index+1}</span><span class="__crossx-wallet-addr">${re(i.address)}</span></span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
2243
- </button>`}).join(""),o=document.createElement("div");return o.id=Z,o.innerHTML=`
2244
- <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ae(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2284
+ </svg>`,bo='<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 js(r){return r.name||`Account ${r.index+1}`}function So(){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 vo=hs().portraitBaseUrl;function Eo(r,e){return e.replace("#",""),`${vo}/portrait/evm/${r}.png?size=56`}function Ys(r,e,s){const t=Eo(r,s),o=So().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='${o}';this.nextElementSibling.style.display='flex';"><span class="__crossx-wallet-avatar-fallback"></span></span>`}function Ao(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(i=>{const a=t&&i.address.toLowerCase()===t,c=a?" __crossx-wallet-item--selected":"",l=a?`<span class="__crossx-wallet-selected">Selected</span><span class="__crossx-wallet-check">${bo}</span>`:"";return`<button class="__crossx-wallet-item${c}" data-wallet-index="${i.index}" data-wallet-address="${C(i.address)}">
2285
+ ${Ys(i.address,i.index,e.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${C(js(i))}</span><span class="__crossx-wallet-addr">${se(i.address)}</span></span>${l}
2286
+ </button>`}).join(""),o=document.createElement("div");return o.id=J,o.innerHTML=`
2287
+ <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ie(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2245
2288
  <div class="__crossx-header">
2246
2289
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
2247
2290
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Select Connected Wallet</p>
2248
2291
  <p class="__crossx-subtitle--body">Please select the wallet you previously used for this game to continue.</p>
2249
2292
  </div>
2250
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2293
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2251
2294
  </div>
2252
2295
  <hr class="__crossx-divider">
2253
2296
  <div class="__crossx-body">
@@ -2264,48 +2307,48 @@ button.__crossx-connect-other-block:active {
2264
2307
  ${n}
2265
2308
  </div>
2266
2309
  <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
2267
- <span class="__crossx-wallet-add-icon">${Jn}</span>
2310
+ <span class="__crossx-wallet-add-icon">${yo}</span>
2268
2311
  <span class="__crossx-wallet-add-label">add a wallet</span>
2269
2312
  </button>
2270
2313
  </div>
2271
2314
  </div>
2272
2315
  </div>
2273
2316
  </div>
2274
- `,o}const Qn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2317
+ `,o}const Io=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2275
2318
  <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"/>
2276
2319
  <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"/>
2277
- </svg>`,eo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2320
+ </svg>`,ko=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
2278
2321
  <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"/>
2279
2322
  <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"/>
2280
2323
  <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"/>
2281
2324
  <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"/>
2282
- </svg>`;function to(r){const e=cs(r);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${Un[r]??""}</span><span class="__crossx-connect-other-wallet-name">${L(e)}</span></span>`}function so(r){if(r.length===0)return"";const e=n=>to(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 ro(r,e=[]){const s=r,t=L(String(e[0])),n=e.length>0?`
2325
+ </svg>`;function To(r){const e=ls(r);return`<span class="__crossx-connect-other-wallet-desc-part"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${ao[r]??""}</span><span class="__crossx-connect-other-wallet-name">${C(e)}</span></span>`}function Ro(r){if(r.length===0)return"";const e=n=>To(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 Oo(r,e=[]){const s=r,t=C(String(e[0])),n=e.length>0?`
2283
2326
  <div class="__crossx-login-or-divider">
2284
2327
  <hr><span>or</span><hr>
2285
2328
  </div>
2286
2329
  <button type="button" class="__crossx-connect-other-block" id="__crossx-connect-other-wallet-btn" data-wallet-id="${t}" aria-labelledby="__crossx-connect-other-heading">
2287
2330
  <span class="__crossx-connect-other-text">
2288
2331
  <span class="__crossx-connect-other-title" id="__crossx-connect-other-heading">Connect with Other Wallets</span>
2289
- <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${so(e)}</span>
2332
+ <span class="__crossx-connect-other-desc __crossx-connect-other-summary">${Ro(e)}</span>
2290
2333
  </span>
2291
- </button>`:"",o=document.createElement("div");return o.id=Z,o.innerHTML=`
2292
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2334
+ </button>`:"",o=document.createElement("div");return o.id=J,o.innerHTML=`
2335
+ <div class="__crossx-card __crossx-card--migration" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2293
2336
  <div class="__crossx-header">
2294
2337
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
2295
2338
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">CROSS Wallet</p>
2296
2339
  <p class="__crossx-subtitle">Sign in instantly with your social account</p>
2297
2340
  </div>
2298
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2341
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2299
2342
  </div>
2300
2343
  <hr class="__crossx-divider">
2301
2344
  <div class="__crossx-body">
2302
2345
  <div class="__crossx-login-btn-row">
2303
2346
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
2304
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${Qn}</span>
2347
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${Io}</span>
2305
2348
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Apple</span>
2306
2349
  </button>
2307
2350
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
2308
- <span class="__crossx-login-icon">${eo}</span>
2351
+ <span class="__crossx-login-icon">${ko}</span>
2309
2352
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Google</span>
2310
2353
  </button>
2311
2354
  </div>${n}
@@ -2314,30 +2357,30 @@ button.__crossx-connect-other-block:active {
2314
2357
  </p>
2315
2358
  </div>
2316
2359
  </div>
2317
- `,o}function no(r,e){const s=r,t=document.createElement("div");t.id=Z;const n=L(e.message).replace(/\n/g,"<br>"),o=e.email?`<div class="__crossx-session-account-card">
2318
- <p class="__crossx-session-account-label">${L(e.accountLabel)}</p>
2319
- <p class="__crossx-session-account-email">${L(e.email)}</p>
2360
+ `,o}function Po(r,e){const s=r,t=document.createElement("div");t.id=J;const n=C(e.message).replace(/\n/g,"<br>"),o=e.email?`<div class="__crossx-session-account-card">
2361
+ <p class="__crossx-session-account-label">${C(e.accountLabel)}</p>
2362
+ <p class="__crossx-session-account-email">${C(e.email)}</p>
2320
2363
  </div>`:"";return t.innerHTML=`
2321
- <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">
2364
+ <div class="__crossx-card __crossx-card--migration" style="${ie(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
2322
2365
  <div class="__crossx-header">
2323
- <p class="__crossx-title" id="__crossx-session-header-title">${L(e.title)}</p>
2324
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2366
+ <p class="__crossx-title" id="__crossx-session-header-title">${C(e.title)}</p>
2367
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2325
2368
  </div>
2326
2369
  <hr class="__crossx-divider">
2327
2370
  <div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
2328
2371
  <div class="__crossx-session-hero">
2329
- <p class="__crossx-session-hero-title">${L(e.title)}</p>
2372
+ <p class="__crossx-session-hero-title">${C(e.title)}</p>
2330
2373
  <p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
2331
2374
  </div>
2332
2375
  ${o}
2333
2376
  <div class="__crossx-btn-row">
2334
- <button class="__crossx-cancel-btn" id="__crossx-session-signout">${L(e.signOutLabel)}</button>
2335
- <button class="__crossx-confirm-btn" id="__crossx-session-signin">${L(e.signInAgainLabel)}</button>
2377
+ <button class="__crossx-cancel-btn" id="__crossx-session-signout">${C(e.signOutLabel)}</button>
2378
+ <button class="__crossx-confirm-btn" id="__crossx-session-signin">${C(e.signInAgainLabel)}</button>
2336
2379
  </div>
2337
2380
  </div>
2338
2381
  </div>
2339
- `,t}function oo(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>':"",o=document.createElement("div");return o.id=Z,o.innerHTML=`
2340
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2382
+ `,t}function Co(r,e=!0){const s=r,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",o=document.createElement("div");return o.id=J,o.innerHTML=`
2383
+ <div class="__crossx-card __crossx-card--migration" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2341
2384
  <div class="__crossx-header">
2342
2385
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
2343
2386
  <p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
@@ -2350,17 +2393,17 @@ button.__crossx-connect-other-block:active {
2350
2393
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
2351
2394
  </div>
2352
2395
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
2353
- <span class="__crossx-recover-icon">${Dn}</span>
2396
+ <span class="__crossx-recover-icon">${ro}</span>
2354
2397
  <span class="__crossx-recover-label">Import from Social Backup</span>
2355
2398
  </button>
2356
2399
  ${n}
2357
2400
  </div>
2358
2401
  </div>
2359
- `,o}function io(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:o=5}=e??{},i=!!t,a=i?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${o}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",f=document.createElement("div");return f.id=Z,f.innerHTML=`
2360
- <div class="__crossx-card __crossx-card--migration" style="${ae(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2402
+ `,o}function No(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:o=5}=e??{},i=!!t,a=i?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${o}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",f=document.createElement("div");return f.id=J,f.innerHTML=`
2403
+ <div class="__crossx-card __crossx-card--migration" style="${ie(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2361
2404
  <div class="__crossx-header">
2362
2405
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2363
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2406
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2364
2407
  </div>
2365
2408
  <hr class="__crossx-divider">
2366
2409
  <div class="__crossx-pin-center">
@@ -2376,11 +2419,11 @@ button.__crossx-connect-other-block:active {
2376
2419
  ${u}
2377
2420
  </div>
2378
2421
  </div>
2379
- `,f}function ao(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()],o=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${o} ${i} ${a}:${c}`}function co(r,e,s){const t=r,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?ao(o):null,a=document.createElement("div");return a.id=Z,a.innerHTML=`
2380
- <div class="__crossx-card __crossx-card--migration" style="${ae(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2422
+ `,f}function Lo(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()],o=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${o} ${i} ${a}:${c}`}function Do(r,e,s){const t=r,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?Lo(o):null,a=document.createElement("div");return a.id=J,a.innerHTML=`
2423
+ <div class="__crossx-card __crossx-card--migration" style="${ie(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2381
2424
  <div class="__crossx-header">
2382
2425
  <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
2383
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2426
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2384
2427
  </div>
2385
2428
  <hr class="__crossx-divider">
2386
2429
  <div class="__crossx-pin-center">
@@ -2396,68 +2439,68 @@ button.__crossx-connect-other-block:active {
2396
2439
  </div>
2397
2440
  </div>
2398
2441
  </div>
2399
- `,{overlay:a,startCountdown:l=>{if(n||!o)return()=>{};const f=setInterval(()=>{Date.now()>=o&&(clearInterval(f),l())},1e3);return()=>clearInterval(f)}}}function lo(r){const s=[r.check1,r.check2].map((t,n)=>`
2442
+ `,{overlay:a,startCountdown:l=>{if(n||!o)return()=>{};const f=setInterval(()=>{Date.now()>=o&&(clearInterval(f),l())},1e3);return()=>clearInterval(f)}}}function Mo(r){const s=[r.check1,r.check2].map((t,n)=>`
2400
2443
  <div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
2401
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${fo}</div>
2402
- <span class="__crossx-pw-notice-item-text">${L(t)}</span>
2444
+ <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Ho}</div>
2445
+ <span class="__crossx-pw-notice-item-text">${C(t)}</span>
2403
2446
  </div>
2404
2447
  `).join("");return`
2405
2448
  <div class="__crossx-header">
2406
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${L(r.title)}</p>
2407
- <p class="__crossx-pw-subtitle">${L(r.headerSubtitle)}</p>
2408
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2449
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${C(r.title)}</p>
2450
+ <p class="__crossx-pw-subtitle">${C(r.headerSubtitle)}</p>
2451
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2409
2452
  </div>
2410
2453
  <hr class="__crossx-divider">
2411
2454
  <div class="__crossx-pw-body">
2412
2455
  <div class="__crossx-pw-fields __crossx-pw-fields--notice">
2413
2456
  <div class="__crossx-pw-notice-header">
2414
2457
  <div class="__crossx-pw-notice-title-row">
2415
- <span class="__crossx-pw-notice-icon">${_o}</span>
2416
- <p class="__crossx-pw-notice-title">${L(r.noticeTitle)}</p>
2458
+ <span class="__crossx-pw-notice-icon">${Fo}</span>
2459
+ <p class="__crossx-pw-notice-title">${C(r.noticeTitle)}</p>
2417
2460
  </div>
2418
- <p class="__crossx-pw-notice-desc">${L(r.noticeDesc)}</p>
2461
+ <p class="__crossx-pw-notice-desc">${C(r.noticeDesc)}</p>
2419
2462
  </div>
2420
2463
  <div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
2421
2464
  ${s}
2422
2465
  </div>
2423
2466
  </div>
2424
2467
  <button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
2425
- data-next-label="${L(r.nextButton)}"
2426
- data-submit-label="${L(r.submitButton)}">
2427
- ${L(r.nextButton)}
2468
+ data-next-label="${C(r.nextButton)}"
2469
+ data-submit-label="${C(r.submitButton)}">
2470
+ ${C(r.nextButton)}
2428
2471
  </button>
2429
2472
  </div>
2430
2473
  <div class="__crossx-home-indicator"></div>
2431
- `}function ut(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">${L(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${L(r.subtitle)}</p>`:"",o=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${L(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',i=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
2432
- ${qs}
2474
+ `}function pt(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">${C(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${C(r.subtitle)}</p>`:"",o=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${C(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',i=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
2475
+ ${Xs}
2433
2476
  <span id="__crossx-pin6-lock-countdown"></span>
2434
- </p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${L(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},(E,S)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${S+1}"${e?" disabled":""}>`).join(""),f=e?" --locked":"",_=Array.from({length:6},(E,S)=>`<div class="__crossx-pin6-dot${f}" data-dot-index="${S}" aria-label="PIN digit ${S+1}"></div>`).join(""),p=e?" --disabled":"",b=`
2477
+ </p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${C(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},(v,S)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${S+1}"${e?" disabled":""}>`).join(""),f=e?" --locked":"",x=Array.from({length:6},(v,S)=>`<div class="__crossx-pin6-dot${f}" data-dot-index="${S}" aria-label="PIN digit ${S+1}"></div>`).join(""),_=e?" --disabled":"",p=`
2435
2478
  <div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
2436
2479
  <div class="__crossx-pin6-numpad-row">
2437
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="1">1</button>
2438
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="2">2</button>
2439
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="3">3</button>
2480
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="1">1</button>
2481
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="2">2</button>
2482
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="3">3</button>
2440
2483
  </div>
2441
2484
  <div class="__crossx-pin6-numpad-row">
2442
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="4">4</button>
2443
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="5">5</button>
2444
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="6">6</button>
2485
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="4">4</button>
2486
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="5">5</button>
2487
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="6">6</button>
2445
2488
  </div>
2446
2489
  <div class="__crossx-pin6-numpad-row">
2447
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="7">7</button>
2448
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="8">8</button>
2449
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="9">9</button>
2490
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="7">7</button>
2491
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="8">8</button>
2492
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="9">9</button>
2450
2493
  </div>
2451
2494
  <div class="__crossx-pin6-numpad-row">
2452
2495
  <button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
2453
- <button type="button" class="__crossx-pin6-numpad-key${p}" data-key="0">0</button>
2454
- <button type="button" class="__crossx-pin6-numpad-key --delete${p}" data-key="backspace" aria-label="Delete">${po}</button>
2496
+ <button type="button" class="__crossx-pin6-numpad-key${_}" data-key="0">0</button>
2497
+ <button type="button" class="__crossx-pin6-numpad-key --delete${_}" data-key="backspace" aria-label="Delete">${Uo}</button>
2455
2498
  </div>
2456
2499
  </div>`;return`
2457
2500
  <div class="__crossx-header">
2458
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${L(r.title)}</p>
2501
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${C(r.title)}</p>
2459
2502
  ${t}
2460
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${oe}</button>
2503
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ne}</button>
2461
2504
  </div>
2462
2505
  <hr class="__crossx-divider">
2463
2506
  <div class="__crossx-pin6-body"${s}>
@@ -2465,7 +2508,7 @@ button.__crossx-connect-other-block:active {
2465
2508
  <div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
2466
2509
  ${u}
2467
2510
  <div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
2468
- ${_}
2511
+ ${x}
2469
2512
  </div>
2470
2513
  </div>
2471
2514
  ${o}
@@ -2473,19 +2516,19 @@ button.__crossx-connect-other-block:active {
2473
2516
  ${c}
2474
2517
  ${i}
2475
2518
  </div>
2476
- ${b}
2477
- `}function is(r,e){const s=document.createElement("div");return s.id=Z,s.innerHTML=`
2478
- <div class="__crossx-card __crossx-card--pin6" style="${ae(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2519
+ ${p}
2520
+ `}function as(r,e){const s=document.createElement("div");return s.id=J,s.innerHTML=`
2521
+ <div class="__crossx-card __crossx-card--pin6" style="${ie(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
2479
2522
  ${e}
2480
2523
  </div>
2481
- `,s}function uo(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((o,i)=>i===0||o===(s[i-1]+1)%10),n=s.every((o,i)=>i===0||o===(s[i-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function ho(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 ht(r,e,s,t,n,o,i){var O,D;let a=!!(o&&o>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),u=()=>r.querySelector("#__crossx-pin6-boxes"),f=()=>r.querySelector("#__crossx-pin6-error"),_=()=>r.querySelector("#__crossx-pin6-lock-msg"),p=()=>r.querySelector("#__crossx-pin6-lock-countdown"),b=()=>r.querySelector(".__crossx-pin6-body"),E=()=>l().map(w=>w.value).join(""),S=()=>Array.from(r.querySelectorAll(".__crossx-pin6-dot")),A=()=>{var v;const w=l(),y=S();if(y.length&&(y.forEach((I,R)=>{const F=!!(w[R]&&w[R].value);I.classList.toggle("--filled",F),I.classList.toggle("--active",!1)}),!a&&!c)){const I=w.findIndex(F=>!F.value);(v=y[I===-1?5:I])==null||v.classList.add("--active")}},k=()=>{r.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(y=>y.classList.toggle("--disabled",a)),S().forEach(y=>y.classList.toggle("--locked",a)),A()},H=w=>{a=w,l().forEach(y=>{y.disabled=w,y.classList.toggle("--locked",w)})},M=()=>r.querySelector("#__crossx-pin6-attempt"),K=()=>{const w=f();w&&(w.textContent="")},q=()=>i??"Your account will be locked after further failures.",Q=()=>r.querySelector("#__crossx-pin6-warning"),W=w=>{var v;let y=Q();if(!y){y=document.createElement("p"),y.className="__crossx-pin6-warning",y.id="__crossx-pin6-warning";const I=f();I?I.insertAdjacentElement("afterend",y):(v=b())==null||v.appendChild(y)}y.textContent=w},J=()=>{const w=Q();w&&(w.textContent="")},ee=(w,y)=>{var I;let v=M();if(!v){v=document.createElement("p"),v.className="__crossx-pin6-attempt",v.id="__crossx-pin6-attempt";const R=Q()??f();R?R.insertAdjacentElement("afterend",v):(I=b())==null||I.appendChild(v)}v.textContent=`${w}/${y}`},U=()=>{const w=M();w&&(w.textContent="")},C=w=>{const y=f();y&&(y.textContent=w);const v=u();v==null||v.classList.add("--shake"),setTimeout(()=>v==null?void 0:v.classList.remove("--shake"),500),l().forEach(I=>{I.value=""}),setTimeout(()=>{var I;(I=l()[0])==null||I.focus(),A()},50)},$=w=>{var F;H(!0),l().forEach(B=>{B.value=""}),k();const y=f();if(y&&(y.textContent="Too many failed attempts. Please wait."),!_()){const B=document.createElement("p");B.className="__crossx-pin6-lock-msg",B.id="__crossx-pin6-lock-msg",B.innerHTML=`${qs}<span id="__crossx-pin6-lock-countdown"></span>`;const N=f();N?N.insertAdjacentElement("afterend",B):(F=b())==null||F.appendChild(B)}const v=()=>{var G;const B=w-Date.now(),N=p();B<=0?(clearInterval(I),H(!1),(G=_())==null||G.remove(),y&&(y.textContent=""),k(),setTimeout(()=>{var X;return(X=l()[0])==null?void 0:X.focus()},50)):N&&(N.textContent=` ${ho(B)}`)},I=setInterval(v,1e3);v();const R=new MutationObserver(()=>{document.contains(r)||(clearInterval(I),R.disconnect())});R.observe(document.body,{childList:!0,subtree:!1})},g=async()=>{if(a||c)return;const w=E();if(w.length===6){c=!0,l().forEach(y=>{y.disabled=!0});try{if(n){const y=await n(w);y.ok?e(w):y.lockExpiresAt?(U(),$(y.lockExpiresAt)):(C(y.error??"Incorrect PIN. Please try again."),y.attemptCount!=null&&y.maxAttempts!=null?(W(q()),ee(y.attemptCount,y.maxAttempts)):(J(),U()))}else e(w)}catch(y){t&&t(y)}finally{c=!1,a||l().forEach(y=>{y.disabled=!1}),A()}}};o&&o>Date.now()?$(o):setTimeout(()=>{var w;return(w=l()[0])==null?void 0:w.focus()},100);const m=()=>{if(a||c)return;const w=l(),y=w.find(v=>!v.value)??w[w.length-1];y==null||y.focus()};(O=u())==null||O.addEventListener("click",w=>{w.target.classList.contains("__crossx-pin6-box")||m()}),(D=b())==null||D.addEventListener("click",w=>{const y=w.target;y.classList.contains("__crossx-pin6-box")||y.closest("button")||m()}),l().forEach((w,y)=>{w.addEventListener("input",()=>{var I;const v=w.value.replace(/\D/g,"").slice(-1);w.value=v,K(),v&&y<5&&((I=l()[y+1])==null||I.focus()),A(),E().length===6&&setTimeout(g,80)}),w.addEventListener("keydown",v=>{var I,R;if(v.key==="Backspace"){if(v.preventDefault(),w.value)w.value="";else if(y>0){const F=l()[y-1];F.value="",F.focus()}A()}else v.key==="ArrowLeft"&&y>0?(v.preventDefault(),(I=l()[y-1])==null||I.focus()):v.key==="ArrowRight"&&y<5?(v.preventDefault(),(R=l()[y+1])==null||R.focus()):v.key==="Escape"&&s()}),w.addEventListener("paste",v=>{var F,B;v.preventDefault();const I=(((F=v.clipboardData)==null?void 0:F.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const R=l();I.split("").forEach((N,G)=>{R[G]&&(R[G].value=N)}),(B=R[Math.min(I.length-1,5)])==null||B.focus(),K(),A(),E().length===6&&setTimeout(g,80)}),w.addEventListener("focus",()=>w.select())});const T=r.querySelector("#__crossx-pin6-numpad");if(T){let w=null;const y=()=>{w&&(w.classList.remove("--pressed"),w=null)};T.addEventListener("pointerdown",I=>{const R=I.target.closest(".__crossx-pin6-numpad-key");!R||a||c||(y(),w=R,R.classList.add("--pressed"),R.setPointerCapture(I.pointerId))});const v=I=>{const R=I.dataset.key;if(!R)return;if(R==="backspace"){const G=[...l()].reverse().find(X=>X.value);G&&(G.value="",K()),A();return}if(!/^\d$/.test(R))return;const B=l().find(N=>!N.value);B&&(B.value=R,K(),A(),E().length===6&&setTimeout(g,80))};T.addEventListener("pointerup",I=>{if(!w)return;const R=w;y();const F=R.getBoundingClientRect();I.clientX>=F.left&&I.clientX<=F.right&&I.clientY>=F.top&&I.clientY<=F.bottom&&!a&&!c&&v(R)}),T.addEventListener("pointercancel",y),T.addEventListener("pointerleave",y,!0),A(),o&&o>Date.now()&&k()}}const po=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
2524
+ `,s}function $o(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((o,i)=>i===0||o===(s[i-1]+1)%10),n=s.every((o,i)=>i===0||o===(s[i-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function Bo(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 ft(r,e,s,t,n,o,i){var O,M;let a=!!(o&&o>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),u=()=>r.querySelector("#__crossx-pin6-boxes"),f=()=>r.querySelector("#__crossx-pin6-error"),x=()=>r.querySelector("#__crossx-pin6-lock-msg"),_=()=>r.querySelector("#__crossx-pin6-lock-countdown"),p=()=>r.querySelector(".__crossx-pin6-body"),v=()=>l().map(y=>y.value).join(""),S=()=>Array.from(r.querySelectorAll(".__crossx-pin6-dot")),I=()=>{var E;const y=l(),b=S();if(b.length&&(b.forEach((A,R)=>{const F=!!(y[R]&&y[R].value);A.classList.toggle("--filled",F),A.classList.toggle("--active",!1)}),!a&&!c)){const A=y.findIndex(F=>!F.value);(E=b[A===-1?5:A])==null||E.classList.add("--active")}},T=()=>{r.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(b=>b.classList.toggle("--disabled",a)),S().forEach(b=>b.classList.toggle("--locked",a)),I()},H=y=>{a=y,l().forEach(b=>{b.disabled=y,b.classList.toggle("--locked",y)})},D=()=>r.querySelector("#__crossx-pin6-attempt"),K=()=>{const y=f();y&&(y.textContent="")},q=()=>i??"Your account will be locked after further failures.",Z=()=>r.querySelector("#__crossx-pin6-warning"),W=y=>{var E;let b=Z();if(!b){b=document.createElement("p"),b.className="__crossx-pin6-warning",b.id="__crossx-pin6-warning";const A=f();A?A.insertAdjacentElement("afterend",b):(E=p())==null||E.appendChild(b)}b.textContent=y},X=()=>{const y=Z();y&&(y.textContent="")},Q=(y,b)=>{var A;let E=D();if(!E){E=document.createElement("p"),E.className="__crossx-pin6-attempt",E.id="__crossx-pin6-attempt";const R=Z()??f();R?R.insertAdjacentElement("afterend",E):(A=p())==null||A.appendChild(E)}E.textContent=`${y}/${b}`},U=()=>{const y=D();y&&(y.textContent="")},N=y=>{const b=f();b&&(b.textContent=y);const E=u();E==null||E.classList.add("--shake"),setTimeout(()=>E==null?void 0:E.classList.remove("--shake"),500),l().forEach(A=>{A.value=""}),setTimeout(()=>{var A;(A=l()[0])==null||A.focus(),I()},50)},$=y=>{var F;H(!0),l().forEach(B=>{B.value=""}),T();const b=f();if(b&&(b.textContent="Too many failed attempts. Please wait."),!x()){const B=document.createElement("p");B.className="__crossx-pin6-lock-msg",B.id="__crossx-pin6-lock-msg",B.innerHTML=`${Xs}<span id="__crossx-pin6-lock-countdown"></span>`;const L=f();L?L.insertAdjacentElement("afterend",B):(F=p())==null||F.appendChild(B)}const E=()=>{var G;const B=y-Date.now(),L=_();B<=0?(clearInterval(A),H(!1),(G=x())==null||G.remove(),b&&(b.textContent=""),T(),setTimeout(()=>{var Y;return(Y=l()[0])==null?void 0:Y.focus()},50)):L&&(L.textContent=` ${Bo(B)}`)},A=setInterval(E,1e3);E();const R=new MutationObserver(()=>{document.contains(r)||(clearInterval(A),R.disconnect())});R.observe(document.body,{childList:!0,subtree:!1})},m=async()=>{if(a||c)return;const y=v();if(y.length===6){c=!0,l().forEach(b=>{b.disabled=!0});try{if(n){const b=await n(y);b.ok?e(y):b.lockExpiresAt?(U(),$(b.lockExpiresAt)):(N(b.error??"Incorrect PIN. Please try again."),b.attemptCount!=null&&b.maxAttempts!=null?(W(q()),Q(b.attemptCount,b.maxAttempts)):(X(),U()))}else e(y)}catch(b){t&&t(b)}finally{c=!1,a||l().forEach(b=>{b.disabled=!1}),I()}}};o&&o>Date.now()?$(o):setTimeout(()=>{var y;return(y=l()[0])==null?void 0:y.focus()},100);const w=()=>{if(a||c)return;const y=l(),b=y.find(E=>!E.value)??y[y.length-1];b==null||b.focus()};(O=u())==null||O.addEventListener("click",y=>{y.target.classList.contains("__crossx-pin6-box")||w()}),(M=p())==null||M.addEventListener("click",y=>{const b=y.target;b.classList.contains("__crossx-pin6-box")||b.closest("button")||w()}),l().forEach((y,b)=>{y.addEventListener("input",()=>{var A;const E=y.value.replace(/\D/g,"").slice(-1);y.value=E,K(),E&&b<5&&((A=l()[b+1])==null||A.focus()),I(),v().length===6&&setTimeout(m,80)}),y.addEventListener("keydown",E=>{var A,R;if(E.key==="Backspace"){if(E.preventDefault(),y.value)y.value="";else if(b>0){const F=l()[b-1];F.value="",F.focus()}I()}else E.key==="ArrowLeft"&&b>0?(E.preventDefault(),(A=l()[b-1])==null||A.focus()):E.key==="ArrowRight"&&b<5?(E.preventDefault(),(R=l()[b+1])==null||R.focus()):E.key==="Escape"&&s()}),y.addEventListener("paste",E=>{var F,B;E.preventDefault();const A=(((F=E.clipboardData)==null?void 0:F.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!A)return;const R=l();A.split("").forEach((L,G)=>{R[G]&&(R[G].value=L)}),(B=R[Math.min(A.length-1,5)])==null||B.focus(),K(),I(),v().length===6&&setTimeout(m,80)}),y.addEventListener("focus",()=>y.select())});const k=r.querySelector("#__crossx-pin6-numpad");if(k){let y=null;const b=()=>{y&&(y.classList.remove("--pressed"),y=null)};k.addEventListener("pointerdown",A=>{const R=A.target.closest(".__crossx-pin6-numpad-key");!R||a||c||(b(),y=R,R.classList.add("--pressed"),R.setPointerCapture(A.pointerId))});const E=A=>{const R=A.dataset.key;if(!R)return;if(R==="backspace"){const G=[...l()].reverse().find(Y=>Y.value);G&&(G.value="",K()),I();return}if(!/^\d$/.test(R))return;const B=l().find(L=>!L.value);B&&(B.value=R,K(),I(),v().length===6&&setTimeout(m,80))};k.addEventListener("pointerup",A=>{if(!y)return;const R=y;b();const F=R.getBoundingClientRect();A.clientX>=F.left&&A.clientX<=F.right&&A.clientY>=F.top&&A.clientY<=F.bottom&&!a&&!c&&E(R)}),k.addEventListener("pointercancel",b),k.addEventListener("pointerleave",b,!0),I(),o&&o>Date.now()&&T()}}const Uo=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
2482
2525
  <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"/>
2483
2526
  <line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
2484
2527
  <line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
2485
- </svg>`,qs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
2528
+ </svg>`,Xs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
2486
2529
  <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"/>
2487
- </svg>`,fo=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
2530
+ </svg>`,Ho=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
2488
2531
  <path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
2489
- </svg>`,_o=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2532
+ </svg>`,Fo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2490
2533
  <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"/>
2491
- </svg>`;function xo(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.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)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,p)=>{t[p]&&(t[p].value=_)});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",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class go{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=ns(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=ns(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var E;le();const o=[...e],i=Zn(o,this.tokens,t),a=Oe();de(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),a())},u=S=>{l(),n(S)},f=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(S=>{S.addEventListener("click",()=>{const A=S.dataset.walletAddress??"",k=parseInt(S.dataset.walletIndex??"0",10);u({address:A,index:k})})})})();const p=i.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const S=await s();o.push(S);const A=i.querySelector("#__crossx-wallet-list");if(A){const k=document.createElement("button");k.className="__crossx-wallet-item",k.dataset.walletIndex=String(S.index),k.dataset.walletAddress=S.address,k.innerHTML=`<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${S.index+1}</span><span class="__crossx-wallet-addr">${re(S.address)}</span></span>`,k.addEventListener("click",()=>u(S)),A.appendChild(k),k.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(E=i.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",f),i.addEventListener("click",S=>{S.target===i&&f()});const b=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",b),f())};document.addEventListener("keydown",b)})}showLoginSelector(e){var t;const s=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(Pe).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var _,p,b,E;le();const o=ro(this.tokens,s),i=Oe();de(o);const a=()=>{o.remove(),i()},c=S=>{a(),n({type:"oauth",provider:S})},l=S=>{a(),n({type:"external",walletId:S})},u=()=>{a(),n(null)};(_=o.querySelector("#__crossx-apple-btn"))==null||_.addEventListener("click",()=>c("apple")),(p=o.querySelector("#__crossx-google-btn"))==null||p.addEventListener("click",()=>c("google")),(b=o.querySelector("#__crossx-connect-other-wallet-btn"))==null||b.addEventListener("click",S=>{const k=S.currentTarget.dataset.walletId??"";k&&l(k)}),(E=o.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",u),o.addEventListener("click",S=>{S.target===o&&u()}),o.querySelectorAll(".__crossx-login-terms-link").forEach(S=>{S.addEventListener("click",A=>A.stopPropagation())});const f=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)})}showSessionAlert(e){return new Promise(s=>{var u,f,_;le();const t=this.messages,n=no(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"}),o=Oe();de(n);let i=!1;const a=()=>{i||(i=!0,n.remove(),o())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;le();const n=oo(this.tokens,s);de(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),s){const u=()=>{o(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const f=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(s=>{le();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"},o={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."},i={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=is(this.tokens,lo(n)),c=Oe();de(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=k=>{u(),s(k)},_=()=>{u(),s(null)},p=a.querySelector(".__crossx-card"),b={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."},E=k=>{var H;p.innerHTML=ut({title:i.title,headerSubtitle:i.headerSubtitle}),(H=p.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",_),ht(p,M=>{M===k?f(k):S(o.mismatchError)},_)},S=k=>{var H;p.innerHTML=ut({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:k}),(H=p.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",_),ht(p,M=>{const K=uo(M,b);K?S(K):E(M)},_)};(()=>{var ee;const k=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),H=p.querySelector("#__crossx-pin-notice-next"),M=new Set;H.removeAttribute("disabled");const K=H.dataset.nextLabel??"Next",q=H.dataset.submitLabel??"I Understand",Q=()=>{const U=M.size===k.length;H.classList.toggle("--disabled",!U),H.textContent=U?q:K},W=(U,C)=>{if(M.has(C))return;const $=U.querySelector(`#__crossx-notice-check-${C}`);M.add(C),$.classList.add("--checked"),U.setAttribute("aria-checked","true"),Q()},J=(U,C)=>{if(!M.has(C))return;const $=U.querySelector(`#__crossx-notice-check-${C}`);M.delete(C),$.classList.remove("--checked"),U.setAttribute("aria-checked","false"),Q()};k.forEach(U=>{const C=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{M.has(C)?J(U,C):W(U,C)}),U.addEventListener("keydown",$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),M.has(C)?J(U,C):W(U,C))})}),H.addEventListener("click",()=>{if(M.size===k.length){S(e==null?void 0:e.errorMessage);return}const U=k.find($=>{const g=parseInt($.dataset.checkIndex??"0",10);return!M.has(g)});if(!U)return;const C=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),W(U,C)},400)}),(ee=p.querySelector("#__crossx-close-btn"))==null||ee.addEventListener("click",_)})(),a.addEventListener("click",k=>{k.target===a&&_()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var A;le();const n=this.messages,o=(e==null?void 0:e.verifyMode)===!0,i=o?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=o?(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=is(this.tokens,ut({title:i,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=Oe();de(l);let f=!1;const _=()=>{f||(f=!0,l.remove(),u())},p=k=>{_(),s(k)},b=()=>{_(),s(null)},E=k=>{_(),t(k)},S=l.querySelector(".__crossx-card");(A=S.querySelector("#__crossx-close-btn"))==null||A.addEventListener("click",b),ht(S,p,b,E,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",k=>{k.target===l&&b()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;le();const t=io(this.tokens,e);de(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};xo(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;le();const{overlay:n,startCountdown:o}=co(this.tokens,e,s);de(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(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;le();const t=zn(e,this.tokens);de(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const f=l.dataset.copy;f&&((_=navigator.clipboard)==null||_.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{le();const n=Vn(e,this.tokens);de(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,f;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(jn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,u,f;le();let t;e.type==="sign-message"?t=Yn(e,this.tokens):e.type==="sign-typed-data"?t=Xn(e,this.tokens):e.type==="sign"?t=Wn(e,this.tokens):t=Gn(e,this.tokens);const n=Oe();de(t);const o=()=>{t.remove(),n()},i=()=>{o(),s(!0)},a=()=>{o(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",i),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",p=>{var E;p.stopPropagation();const b=_.dataset.copy;b&&((E=navigator.clipboard)==null||E.writeText(b).catch(()=>{}))})}),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Ks{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 mo(r,e){r.debug;const s=Ce.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},o=t.authMode!=="cookie"&&Ft.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new Ft(r.projectId):new pr,a=new Sn,c=new An,l=new Ie,u=new Ks,f=new mt;let _;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new kn(i,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Ae(n,i,c,u,f));const p=new Fe(n,c),b=new go(r.theme??"light",r.themeTokens),E=e!=null&&e.wrapConfirmation?e.wrapConfirmation(b):b,S=new Ve(t,n,i,a,c,l,_,u,E,p,f);return typeof window<"u"&&(window.__crossxSDK=S),S}function wo(r){const e=yo(r),s=bo(e),t=JSON.parse(s);vo(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 yo(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 bo(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=So(r);return decodeURIComponent(e)}function So(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 vo(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 필드가 없습니다")}exports.CONNECT_OTHER_WALLET_DISPLAY_ORDER=as;exports.CROSSxError=x;exports.CROSSxEthereumProvider=ls;exports.CROSSxSDK=Ve;exports.ChainId=Xs;exports.ConnectOtherWalletItem=Pe;exports.ErrorCode=h;exports.PinMemoryStore=mt;exports.TokenMemoryStore=Ks;exports.createCROSSxSDK=mo;exports.getConnectOtherWalletLabel=cs;exports.parseOAuthDeeplink=wo;
2534
+ </svg>`;function Wo(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.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)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((x,_)=>{t[_]&&(t[_].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",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class Go{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=os(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=os(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var v;ce();const o=[...e],i=Ao(o,this.tokens,t),a=Oe();le(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),a())},u=S=>{l(),n(S)},f=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(S=>{S.addEventListener("click",()=>{const I=S.dataset.walletAddress??"",T=parseInt(S.dataset.walletIndex??"0",10),H=o.find(D=>D.index===T);u({address:I,index:T,name:H==null?void 0:H.name})})})})();const _=i.querySelector("#__crossx-add-wallet-btn");_&&_.addEventListener("click",async()=>{_.disabled=!0;try{const S=await s();o.push(S);const I=i.querySelector("#__crossx-wallet-list");if(I){const T=document.createElement("button");T.className="__crossx-wallet-item",T.dataset.walletIndex=String(S.index),T.dataset.walletAddress=S.address,T.innerHTML=`${Ys(S.address,S.index,this.tokens.bg)}<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">${C(js(S))}</span><span class="__crossx-wallet-addr">${se(S.address)}</span></span>`,T.addEventListener("click",()=>u(S)),I.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{_.disabled=!1}}),(v=i.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",f),i.addEventListener("click",S=>{S.target===i&&f()});const p=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",p),f())};document.addEventListener("keydown",p)})}showLoginSelector(e){var t;const s=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(Ce).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var x,_,p,v;ce();const o=Oo(this.tokens,s),i=Oe();le(o);const a=()=>{o.remove(),i()},c=S=>{a(),n({type:"oauth",provider:S})},l=S=>{a(),n({type:"external",walletId:S})},u=()=>{a(),n(null)};(x=o.querySelector("#__crossx-apple-btn"))==null||x.addEventListener("click",()=>c("apple")),(_=o.querySelector("#__crossx-google-btn"))==null||_.addEventListener("click",()=>c("google")),(p=o.querySelector("#__crossx-connect-other-wallet-btn"))==null||p.addEventListener("click",S=>{const T=S.currentTarget.dataset.walletId??"";T&&l(T)}),(v=o.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",u),o.addEventListener("click",S=>{S.target===o&&u()}),o.querySelectorAll(".__crossx-login-terms-link").forEach(S=>{S.addEventListener("click",I=>I.stopPropagation())});const f=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)})}showSessionAlert(e){return new Promise(s=>{var u,f,x;ce();const t=this.messages,n=Po(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"}),o=Oe();le(n);let i=!1;const a=()=>{i||(i=!0,n.remove(),o())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.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;ce();const n=Co(this.tokens,s);le(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),s){const u=()=>{o(),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 f=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(s=>{ce();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"},o={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."},i={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=as(this.tokens,Mo(n)),c=Oe();le(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=T=>{u(),s(T)},x=()=>{u(),s(null)},_=a.querySelector(".__crossx-card"),p={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."},v=T=>{var H;_.innerHTML=pt({title:i.title,headerSubtitle:i.headerSubtitle}),(H=_.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",x),ft(_,D=>{D===T?f(T):S(o.mismatchError)},x)},S=T=>{var H;_.innerHTML=pt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:T}),(H=_.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",x),ft(_,D=>{const K=$o(D,p);K?S(K):v(D)},x)};(()=>{var Q;const T=Array.from(_.querySelectorAll(".__crossx-pw-notice-item")),H=_.querySelector("#__crossx-pin-notice-next"),D=new Set;H.removeAttribute("disabled");const K=H.dataset.nextLabel??"Next",q=H.dataset.submitLabel??"I Understand",Z=()=>{const U=D.size===T.length;H.classList.toggle("--disabled",!U),H.textContent=U?q:K},W=(U,N)=>{if(D.has(N))return;const $=U.querySelector(`#__crossx-notice-check-${N}`);D.add(N),$.classList.add("--checked"),U.setAttribute("aria-checked","true"),Z()},X=(U,N)=>{if(!D.has(N))return;const $=U.querySelector(`#__crossx-notice-check-${N}`);D.delete(N),$.classList.remove("--checked"),U.setAttribute("aria-checked","false"),Z()};T.forEach(U=>{const N=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{D.has(N)?X(U,N):W(U,N)}),U.addEventListener("keydown",$=>{($.key===" "||$.key==="Enter")&&($.preventDefault(),D.has(N)?X(U,N):W(U,N))})}),H.addEventListener("click",()=>{if(D.size===T.length){S(e==null?void 0:e.errorMessage);return}const U=T.find($=>{const m=parseInt($.dataset.checkIndex??"0",10);return!D.has(m)});if(!U)return;const N=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),W(U,N)},400)}),(Q=_.querySelector("#__crossx-close-btn"))==null||Q.addEventListener("click",x)})(),a.addEventListener("click",T=>{T.target===a&&x()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var I;ce();const n=this.messages,o=(e==null?void 0:e.verifyMode)===!0,i=o?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=o?(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=as(this.tokens,pt({title:i,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=Oe();le(l);let f=!1;const x=()=>{f||(f=!0,l.remove(),u())},_=T=>{x(),s(T)},p=()=>{x(),s(null)},v=T=>{x(),t(T)},S=l.querySelector(".__crossx-card");(I=S.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",p),ft(S,_,p,v,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",T=>{T.target===l&&p()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;ce();const t=No(this.tokens,e);le(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};Wo(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;ce();const{overlay:n,startCountdown:o}=Do(this.tokens,e,s);le(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(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;ce();const t=_o(e,this.tokens);le(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var x;u.stopPropagation();const f=l.dataset.copy;f&&((x=navigator.clipboard)==null||x.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{ce();const n=xo(e,this.tokens);le(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,f;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.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=>{i||(go(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,u,f;ce();let t;e.type==="sign-message"?t=mo(e,this.tokens):e.type==="sign-typed-data"?t=wo(e,this.tokens):e.type==="sign"?t=uo(e,this.tokens):t=ho(e,this.tokens);const n=Oe();le(t);const o=()=>{t.remove(),n()},i=()=>{o(),s(!0)},a=()=>{o(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",i),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",_=>{var v;_.stopPropagation();const p=x.dataset.copy;p&&((v=navigator.clipboard)==null||v.writeText(p).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 Js{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 qo(r,e){r.debug;const s=Ne.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},o=t.authMode!=="cookie"&&Ft.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new Ft(r.projectId):new Dr,a=new qn,c=new jn,l=new Ee,u=new Js,f=new yt;let x;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),x=new Xn(i,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),x=new Ae(n,i,c,u,f));const _=new He(n,c),p=new Go(r.theme??"light",r.themeTokens),v=e!=null&&e.wrapConfirmation?e.wrapConfirmation(p):p,S=new je(t,n,i,a,c,l,x,u,v,_,f);return typeof window<"u"&&(window.__crossxSDK=S),S}function Ko(r){const e=Vo(r),s=zo(e),t=JSON.parse(s);Yo(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 Vo(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 zo(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=jo(r);return decodeURIComponent(e)}function jo(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 Yo(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 필드가 없습니다")}exports.CONNECT_OTHER_WALLET_DISPLAY_ORDER=cs;exports.CROSSxError=g;exports.CROSSxEthereumProvider=ds;exports.CROSSxSDK=je;exports.ChainId=sr;exports.ConnectOtherWalletItem=Ce;exports.ErrorCode=h;exports.PinMemoryStore=yt;exports.TokenMemoryStore=Js;exports.createCROSSxSDK=qo;exports.getConnectOtherWalletLabel=ls;exports.parseOAuthDeeplink=Ko;