@nexus-cross/crossx-sdk-core 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/__tests__/adapters/BrowserOAuthAdapter.test.d.ts +2 -0
  2. package/dist/__tests__/adapters/BrowserOAuthAdapter.test.d.ts.map +1 -0
  3. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts +4 -3
  4. package/dist/__tests__/mocks/MockWalletProviderPort.d.ts.map +1 -1
  5. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +18 -15
  6. package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
  7. package/dist/adapters/crypto/JoseCryptoAdapter.d.ts +1 -1
  8. package/dist/adapters/crypto/JoseCryptoAdapter.d.ts.map +1 -1
  9. package/dist/adapters/oauth/BrowserOAuthAdapter.d.ts +9 -1
  10. package/dist/adapters/oauth/BrowserOAuthAdapter.d.ts.map +1 -1
  11. package/dist/adapters/transport/FetchTransportAdapter.d.ts.map +1 -1
  12. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts +15 -15
  13. package/dist/adapters/wallet/MockWalletProviderAdapter.d.ts.map +1 -1
  14. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts +23 -14
  15. package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
  16. package/dist/adapters/wallet/types.d.ts +7 -7
  17. package/dist/adapters/wallet/types.d.ts.map +1 -1
  18. package/dist/core/i18n/messages.en.d.ts.map +1 -1
  19. package/dist/core/i18n/messages.ko.d.ts.map +1 -1
  20. package/dist/core/i18n/types.d.ts +28 -29
  21. package/dist/core/i18n/types.d.ts.map +1 -1
  22. package/dist/core/ports/ConfirmationPort.d.ts +19 -18
  23. package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
  24. package/dist/core/ports/TransportPort.d.ts.map +1 -1
  25. package/dist/core/ports/WalletProviderPort.d.ts +14 -8
  26. package/dist/core/ports/WalletProviderPort.d.ts.map +1 -1
  27. package/dist/core/services/PinMemoryStore.d.ts +43 -0
  28. package/dist/core/services/PinMemoryStore.d.ts.map +1 -0
  29. package/dist/core/services/TypedEventEmitter.d.ts.map +1 -1
  30. package/dist/core/types/caip.d.ts.map +1 -1
  31. package/dist/core/types/chain.d.ts +1 -1
  32. package/dist/core/types/chain.d.ts.map +1 -1
  33. package/dist/core/types/errors.d.ts +15 -11
  34. package/dist/core/types/errors.d.ts.map +1 -1
  35. package/dist/core/types/index.d.ts.map +1 -1
  36. package/dist/core/usecases/SignInUseCase.d.ts +10 -0
  37. package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
  38. package/dist/core/utils/logger.d.ts.map +1 -1
  39. package/dist/crossx.global +353 -196
  40. package/dist/index.cjs +353 -196
  41. package/dist/index.js +2680 -2208
  42. package/dist/sdk/CROSSxSDK.d.ts +80 -41
  43. package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
  44. package/dist/sdk/EthereumProvider.d.ts.map +1 -1
  45. package/package.json +2 -1
@@ -1,8 +1,8 @@
1
- var CROSSx=function(Q){"use strict";var Sn=Object.defineProperty;var En=(Q,p,m)=>p in Q?Sn(Q,p,{enumerable:!0,configurable:!0,writable:!0,value:m}):Q[p]=m;var S=(Q,p,m)=>En(Q,typeof p!="symbol"?p+"":p,m);var p=(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.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",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.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.PASSWORD_NOT_SET="PASSWORD_NOT_SET",r.PASSWORD_WRONG="PASSWORD_WRONG",r.PASSWORD_COMPLEXITY="PASSWORD_COMPLEXITY",r.PASSWORD_CANCELLED="PASSWORD_CANCELLED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class m extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Me={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}},Ms=Object.fromEntries(Object.entries(Me).map(([r,e])=>[r,e.caipId])),$s=new Map(Object.values(Me).map(r=>[r.caipId,r]));new Map(Object.values(Me).map(r=>[r.chainId,r]));const Bs={symbol:"",decimals:18};function tt(r){var e;return((e=$s.get(r))==null?void 0:e.nativeCurrency)??Bs}class Et{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 m(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(p.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(o=>o(...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 ve=null;function In(r){}function It(r){ve=r}const h={log(...r){if(ve){ve.log(...r);return}},warn(...r){if(ve){ve.warn(...r);return}},error(...r){if(ve){ve.error(...r);return}}},Us={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로 계속하기",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",pinInput_title:"PIN 입력",pinInput_placeholder:"4자리 PIN을 입력하세요",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",passwordNotice_headerSubtitle:"트랜잭션, PK/니모닉 및 계정 삭제 시 필요합니다.",passwordNotice_title:"비밀번호 설정 주의사항",passwordNotice_description:"보안을 위해 이 비밀번호는 재설정하거나 복구할 수 없습니다. 반드시 백업하거나 암기해 두시기 바랍니다.",passwordNotice_check1:"이 비밀번호는 분실 시 복구할 수 없으며, 안전하게 백업해 두었습니다.",passwordNotice_check2:"비밀번호 분실 시 계정 및 모든 관련 데이터에 영구적으로 접근이 불가능해질 수 있습니다.",passwordNotice_check3:"지원팀을 포함한 제3자는 이 비밀번호를 복구하거나 재설정해 줄 수 없습니다.",passwordNotice_nextButton:"다음",passwordNotice_submitButton:"동의합니다",passwordSetup_title:"비밀번호 만들기",passwordSetup_subtitle:"비밀번호는 자산 전송 시에만 사용됩니다.",passwordSetup_newPasswordLabel:"새 비밀번호",passwordSetup_confirmPasswordLabel:"새 비밀번호 확인",passwordSetup_rule_minLength:"8자 이상",passwordSetup_rule_uppercase:"대문자 1자 이상 포함",passwordSetup_rule_number:"숫자 1자 이상 포함",passwordSetup_rule_special:"특수문자 1자 이상 포함",passwordSetup_confirmError:"비밀번호가 일치하지 않습니다",passwordSetup_submitButton:"다음",passwordInput_title:"비밀번호 입력",passwordInput_subtitle:"계속하려면 비밀번호를 입력하세요.",passwordInput_passwordLabel:"비밀번호",passwordInput_submitButton:"확인",passwordInput_error:"비밀번호가 올바르지 않습니다. 다시 시도해 주세요.",verifyPassword_title:"비밀번호 확인",verifyPassword_subtitle:"계속하려면 현재 비밀번호를 확인해 주세요.",verifyPassword_passwordLabel:"비밀번호 확인"},At={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",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",pinInput_title:"Enter PIN",pinInput_placeholder:"Enter your 4-digit PIN",pinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",passwordNotice_headerSubtitle:"Required for Transactions, PK/Mnemonic & Account Deletion.",passwordNotice_title:"Password Setup Notice",passwordNotice_description:"For your security, this password cannot be reset or recovered. Please ensure you have it backed up or memorized.",passwordNotice_check1:"This password cannot be recovered if lost, and I have securely backed it up.",passwordNotice_check2:"Losing this password may result in permanent loss of access to my account and all associated data.",passwordNotice_check3:"No third party, including the support team, can recover or reset this password on my behalf.",passwordNotice_nextButton:"Next",passwordNotice_submitButton:"I Understand",passwordSetup_title:"Create Password",passwordSetup_subtitle:"Password is only used to transfer your asset.",passwordSetup_newPasswordLabel:"New Password",passwordSetup_confirmPasswordLabel:"Confirm New Password",passwordSetup_rule_minLength:"Over 8 letters",passwordSetup_rule_uppercase:"Include at least 1 uppercase letter",passwordSetup_rule_number:"Include at least 1 number",passwordSetup_rule_special:"Include at least 1 special character",passwordSetup_confirmError:"Password is incorrect",passwordSetup_submitButton:"Next",passwordInput_title:"Enter Password",passwordInput_subtitle:"Enter your password to continue.",passwordInput_passwordLabel:"Password",passwordInput_submitButton:"Confirm",passwordInput_error:"Incorrect password. Please try again.",verifyPassword_title:"Verify Your Password",verifyPassword_subtitle:"To continue, please confirm your current password",verifyPassword_passwordLabel:"Confirm Password"},Fs={ko:Us,en:At};function Tt(r="en",e){return Fs[r]??At}const st="crossx_access_token",$e="crossx_refresh_token",Be="crossx_user_info";class Hs{constructor(e,s,t,o,n,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=o,this.transport=n,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new m(p.AUTH_FAILED,`${s} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const o=t;if(o.code&&o.code!==200&&o.code>0)throw new m(p.AUTH_FAILED,`${s} 실패 (코드 ${o.code}): ${o.message}`)}}async execute(e){var o,n,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:u}=this.config,g=`${d}${l}`;h.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,g);const _=await this.oauth.openAuth({authUrl:g,expectedOrigin:new URL(d).origin});h.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",_.length,")");const{accessToken:f,refreshToken:b}=await this.exchangeFirebaseToken(_,u);let y,E;try{const U=this.crypto.decodeJWT(_);E=(o=U.firebase)==null?void 0:o.sign_in_provider;const M=((n=U.firebase)==null?void 0:n.identities)??{};E==="google.com"?y=(i=M["google.com"])==null?void 0:i[0]:E==="apple.com"&&(y=(a=M["apple.com"])==null?void 0:a[0]),h.log("[CROSSx] OAuth provider sub 추출 — provider:",E,"hasProviderSub:",!!y)}catch{h.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const U=this.crypto.decodeJWT(f);h.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const M=await this.crypto.verifyJWT(f);if(t=M.signatureVerified??!1,!M.valid)throw h.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const B=M.payload;s={id:B.sub,email:B.email,signInProvider:E,providerSub:y},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(st,f),b&&await this.storage.set($e,b))}else{const U=this.crypto.decodeJWT(_);s={id:U.sub,email:U.email,signInProvider:E,providerSub:y},h.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}h.log("[CROSSx] 사용자 정보 — id:",s.id);const D=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Be,D),h.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return h.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return h.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,o=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;h.log("[CROSSx] Firebase 토큰 교환 요청:",o);const n=await this.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});h.log("[CROSSx] 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return h.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new m(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");h.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 n=t.data,i=n.access_token??n.token;if(typeof i=="string")return i}const o=t.access_token??t.token;if(typeof o=="string")return o}}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 n=t.data,i=n.refresh_token??n.refresh;if(typeof i=="string")return i}const o=t.refresh_token??t.refresh;if(typeof o=="string")return o}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const o=await this.storage.get(Be);if(o)return h.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(o,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){h.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(st),o=await this.storage.get($e);if(h.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",o?"있음":"없음"),!o)return h.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const n=await this.silentRefresh(o);h.log("[CROSSx] restoreSession — silentRefresh 결과:",n?"토큰 발급 성공":"토큰 없음"),n&&this.tokenStore.set(n)}const s=await this.storage.get(Be);if(h.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;h.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return h.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return h.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove($e),await this.storage.remove(Be),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,o=`${s}/cross-auth/social/refresh/simple`,n={};if(!t){const l=this.tokenStore.get()??"";l&&(n.access_token=l),e&&(n.refresh_token=e)}const i=await this.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:n,...t?{credentials:"include"}:{}});h.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){h.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new m(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(st,c);const l=this.extractRefreshToken(a);l&&await this.storage.set($e,l)}return h.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,o=!1;try{if(typeof this.walletProvider.checkWallet=="function"){h.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const n=await this.walletProvider.checkWallet();if(h.log("[CROSSx] 지갑 상태:",n),n==="migration_required")h.log("[CROSSx] migration_required → needsMigration = true"),o=!0;else if(n==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,h.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):h.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){h.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else h.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,h.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(n){if(n instanceof m&&n.code===p.MIGRATION_BACKUP_EXISTS)h.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),o=!0;else{if(n instanceof m&&(n.code===p.PROJECT_NOT_REGISTERED||n.code===p.PROJECT_ID_MISSING||n.code===p.ORIGIN_NOT_ALLOWED))throw h.error("[CROSSx] 프로젝트 설정 에러:",n.message),n;h.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",n)}}return h.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",o),{success:!0,address:t,user:e,needsMigration:o,tokenSignatureVerified:s}}}const Gs="crossx_access_token",Ws="crossx_refresh_token",qs="crossx_user_info";class Vs{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(Gs),await this.storage.remove(Ws)),await this.storage.remove(qs)}}class Ks{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new m(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");h.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return h.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Rt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const o=new Uint8Array(s.length);for(let n=0;n<s.length;n++)o[n]=s[n]^t[n];s.fill(0),this.xorKey=t,this.encryptedBytes=o}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 js{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const o=await this.chainRegistry.getChain(t),n={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:o.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:n})).data;if(a!=null&&a.error)throw new m(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class zs{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(o=>o(s))}removeAllListeners(){this.listeners.clear()}}const Ue={production:{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"},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 Js(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}function Ys(){try{if(typeof window.__CROSSX_CONFIG__<"u"){const r=typeof window.__CROSSX_CONFIG__=="string"?JSON.parse(window.__CROSSX_CONFIG__):window.__CROSSX_CONFIG__,e=Js(r);if(e)return e}}catch{}return Ue.production}const Zs=2e3,Ct=6e4,Xs=1e3,Qs=1e4,er="0x77359400",Ot="0x3B9ACA00",kt=130,Pt=6,Nt=18,tr=0,sr=30*1e3,se=class se extends zs{constructor(e,s,t,o,n,i,a,c,l,d,u){super(),this.storage=t,this.crypto=o,this.transport=n,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPasswordMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&It(e.logger),this.confirmation=l,this.passwordStore=u??new Rt,this.chainRegistry=d,this.jsonRpc=new js(d,n),this.signInUseCase=new Hs(this.internalConfig,t,o,i,n,a,c),this.signOutUseCase=new Vs(this.internalConfig,t,c),this.migrateWalletUseCase=new Ks(t,a)}get config(){return this._config}async initialize(){if(this.initialized)return this.authenticated?{success:!0,address:this.address??void 0}:null;console.log("[CROSSx SDK] v1.1.0 초기화 중..."),this.confirmation.setMessages(Tt(this._config.locale));try{const e=Ys();this.internalConfig.oauthServiceUrl=e.oauthServiceUrl,this.internalConfig.authApiUrl=e.authApiUrl,this.internalConfig.walletGatewayUrl=e.walletGatewayUrl,this.adapterConfig.gatewayUrl=e.walletGatewayUrl;const s=await this.signInUseCase.restoreSession();if(s!=null&&s.success){this.applyAuthResult(s);try{await this.loadWalletAfterAuth()}catch(t){if(!(t instanceof m&&t.code===p.PASSWORD_CANCELLED))throw t;h.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(s!=null&&s.success)}),s??null}catch(e){throw new m(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",e)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new m(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:n}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??n,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),o=await this.selectWalletIfMultiple(t);return{...s,address:(o==null?void 0:o.address)??s.address,addresses:t}}catch(t){throw t instanceof m&&t.code===p.PASSWORD_CANCELLED&&(h.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>h.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}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 m&&s.code===p.PASSWORD_CANCELLED||h.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 m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),h.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof m?s:new m(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:0}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await 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 m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await 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.ensurePasswordForSigning();const o=s.length,i={address:(await this.walletProvider.getAddress(this.userId,o)).address,index:o};return s.push(i),i},e);return t&&(this.address=t.address,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof m?e:new m(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof m?s:new m(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}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(Tt(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");h.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(h.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;h.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}e==="exists"?await this.ensureVerifiedPassword():await this.ensurePasswordSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),h.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;h.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const o=await this.handleMigrationFlow(t);if(o)return this.address=o.address,this.emit("addressChanged",{address:o.address,index:0}),{address:o.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return h.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=t==null?void 0:t.index,n=await this.walletProvider.getAddress(this.userId,o??0);let i;if(this.walletProvider.prepare&&(i=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const c=await this.withPasswordRetry(()=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,n.address));return this.verifySignatureSigner(s,c.signature,n.address),{chainId:e,signature:c.signature,message:s,address:n.address}}catch(c){throw c instanceof m?c:new m(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new m(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");await this.ensurePasswordForSigning(),se.validateTypedDataChainId(e,s);const o=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let n;if(this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:o.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const a=await this.withPasswordRetry(()=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,n,o.address));return se.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:o.address}}catch(a){throw a instanceof m?a:new m(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(se.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=await this.withResolvedGasAndFee(s,e);let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign",{tx:o})).uuid);const i=tt(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:o.from,to:o.to,value:o.value,data:o.data,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const c=await this.withPasswordRetry(()=>this.walletProvider.signTransaction(this.userId,e,o,t==null?void 0:t.index,n));return se.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof m)throw c;const l=c instanceof Error?c.message:String(c);throw new m(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=await this.withResolvedGasAndFee(s,e);let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("send",{tx:o})).uuid);const i=tt(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:o.from,to:o.to,value:o.value,data:o.data,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const c=await this.withPasswordRetry(async()=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,o,n)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,o,t==null?void 0:t.index,n);return l.txHash??l.signature});return{chainId:e,txHash:c,status:"pending"}}catch(c){if(c instanceof m)throw c;const l=c instanceof Error?c.message:String(c);throw new m(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const o=t.intervalMs??Xs,n=Qs,i=t.timeoutMs??Ct,a=Date.now()+i;let c=o;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,n)}throw new m(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,y;const{intervalMs:o,timeoutMs:n,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=o??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Zs,l=n??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??Ct,d=tt(e),u=s.from??"";let g,_;const f=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{g=E;const D=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),U=s.value?BigInt(s.value):0n,M=se.formatTxAmount(s.value,d.symbol,d.decimals),B=se.formatTxAmount("0x"+D.toString(16),d.symbol,d.decimals),j=se.formatTxAmount("0x"+(U+D).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:E.from,to:E.to??s.to,amount:M,fees:B,total:j,nativeSymbol:d.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(_=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:u,to:s.to,amount:se.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:u,to:s.to},f),_)throw _;return{chainId:e,txHash:a,receipt:g}}setPassword(e){this.passwordStore.set(e)}clearPassword(){this.passwordStore.clear()}hasPassword(){return this.passwordStore.has()}async changePassword(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePassword!="function")throw new m(p.NOT_IMPLEMENTED,"changePassword가 구현되어 있지 않습니다");this.passwordStore.set(e);try{await t.changePassword(e,s),this.passwordStore.set(s),h.log("[CROSSx] 비밀번호 변경 완료")}catch(o){throw o instanceof m?o:new m(p.UNKNOWN_ERROR,"비밀번호 변경에 실패했습니다",o)}}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 m(p.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(o){const n=o instanceof Error?o.message:String(o);throw new m(p.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${n}`,o)}}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 m(p.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 m(p.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 m)throw t;const o=t instanceof Error?t.message:String(t);throw new m(p.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${o}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const o=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:o,formatted:se.formatWei(o),chainId:e}}catch(t){if(t instanceof m)throw t;const o=t instanceof Error?t.message:String(t);throw new m(p.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${o}`,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(Nt),o=s/t,i=(s%t).toString().padStart(Nt,"0").replace(/0+$/,"").slice(0,Pt);return i?`${o}.${i}`:`${o}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Et(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(o){if(o instanceof m)throw o;const n=o instanceof Error?o.message:String(o);throw new m(p.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${n}`,o)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const o=BigInt(e);if(o===0n)return;const n=10n**BigInt(t),i=o/n,c=(o%n).toString().padStart(t,"0").slice(0,Pt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;h.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(h.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return h.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,o=0,n=5,i=null;for(;;){o++,h.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${n})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showPinInputPrompt({errorMessage:t,attemptCount:o>1?o-1:void 0,maxAttempts:n});if(l===null)return h.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;h.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${l.length}자리) — verify-pin API 호출`),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyPin)==null?void 0:c.call(a,l,e));if(!d){h.log("[CROSSx][Migration Phase 4] verifyPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){h.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const u=d.pinStatus;if(n=u.maxAttempts,o=n-u.remainingAttempts,u.remainingAttempts===0&&u.lockExpiresAt){const g=u.lockExpiresAt*1e3,_=Math.max(1,Math.round((g-Date.now())/1e3)),f=_<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";h.warn(`[CROSSx][Migration Phase 4] verify-pin 잠금 — ${_}초, 메시지: ${f}`),await this.confirmation.showPinLockedPrompt(_,f),o=0,t="Your account lock has been lifted. You may try again."}else h.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${n})`),t="Incorrect PIN."}catch(d){if(!(d instanceof m))throw d;if(d.code===p.MIGRATION_PIN_LOCKED){const u=d.details;if(n=(u==null?void 0:u.maxAttempts)??5,(u==null?void 0:u.permanent)===!0)return h.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-pin)"),await this.confirmation.showPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const g=((u==null?void 0:u.lockExpiresAt)??0)*1e3,_=Math.max(1,Math.round((g-Date.now())/1e3)),f=_<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";h.warn(`[CROSSx][Migration Phase 4] verify-pin 이미 잠금 — ${_}초`),await this.confirmation.showPinLockedPrompt(_,f),o=0,t="Your account lock has been lifted. You may try again."}else throw h.error("[CROSSx][Migration Phase 4] verify-pin 실패 (복구 불가):",d),d}}h.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePasswordSetup();const l=await this.migrateWalletUseCase.execute(i,e);return h.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof m&&l.code===p.MIGRATION_FAILED)return h.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw h.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),o=e.nonce===void 0||e.nonce===null,n=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!o&&!n&&!i&&!a)return e;const c={...e};if(o){const l=c.from??this.address;if(l){h.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),h.log("[CROSSx] nonce 결과:",c.nonce)}}if(n&&(h.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),h.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){h.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=Ot;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,h.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=er,h.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Ot,h.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=se.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const o=e.match(/^eip155:(\d+)$/);if(o){const n=Number(o[1]);if(t===void 0)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==n)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${n})와 일치하지 않습니다`)}}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 o=Number(t);return Number.isFinite(o)?o:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new m(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==kt)throw new m(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${kt} 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 m(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new m(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const o=this.crypto.recoverPersonalSignSigner(e,s);if(o.toLowerCase()!==t.toLowerCase())throw h.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:o}),new m(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${o}`);h.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(o){if(o instanceof m)throw o;h.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",o)}}applyAuthResult(e){var s,t,o,n;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((o=e.user)==null?void 0:o.providerSub)??null,this.loginType=se.normalizeLoginType((n=e.user)==null?void 0:n.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.passwordStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePasswordSetup(){if(this.passwordStore.has())return;const e=await this.confirmation.showPasswordSetupPrompt();if(!e)throw new m(p.PASSWORD_CANCELLED,"사용자가 비밀번호 설정을 취소했습니다");this.passwordStore.set(e),h.log("[CROSSx] 비밀번호 설정 완료 (메모리 캐시)")}async ensurePasswordForSigning(e){if(this.passwordStore.has()&&!e)return;e&&this.passwordStore.clear();const s=await this.confirmation.showPasswordInputPrompt({errorMessage:e});if(!s)throw new m(p.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");this.passwordStore.set(s),h.log("[CROSSx] 비밀번호 입력 완료 (메모리 캐시)")}async ensureVerifiedPassword(e){if(e)this.passwordStore.clear();else if(this.passwordStore.has())return;if(this._verifyPasswordMutex&&!e){h.log("[CROSSx] ensureVerifiedPassword: 진행 중인 검증 대기"),await this._verifyPasswordMutex;return}let s,t;this._verifyPasswordMutex=new Promise((o,n)=>{s=o,t=n});try{if(typeof this.walletProvider.verifyPassword!="function"){const n=await this.confirmation.showPasswordInputPrompt({verifyMode:!0,errorMessage:e});if(!n)throw new m(p.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");this.passwordStore.set(n),h.log("[CROSSx] 비밀번호 캐시 완료 (verifyPassword 미지원, 로컬 전용)"),s();return}if(!await this.confirmation.showPasswordInputPrompt({verifyMode:!0,errorMessage:e,onSubmit:async n=>{this.passwordStore.set(n);try{return await this.walletProvider.verifyPassword(n)?(h.log("[CROSSx] 비밀번호 서버 검증 완료 (verify-password)"),{ok:!0}):(this.passwordStore.clear(),{ok:!1,error:"Incorrect password. Please try again."})}catch(i){if(this.passwordStore.clear(),i instanceof m&&i.code===p.PASSWORD_WRONG)return{ok:!1,error:"Incorrect password. Please try again."};throw i}}}))throw new m(p.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");s()}catch(o){throw t(o),o}finally{this._verifyPasswordMutex=null}}async loadWalletAfterAuth(){if(!this.userId)return;const e=await this.fetchWalletStatus();if(h.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",e),e!=="exists")return;const s=await this.walletProvider.getAddresses(this.userId);if(s.length>0){this.address=s[0].address,this.emit("addressChanged",{address:s[0].address,index:s[0].index}),h.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address);return}h.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPassword();const t=await this.walletProvider.getAddress(this.userId,0);this.address=t.address,this.emit("addressChanged",{address:t.address,index:0}),h.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address)}async withPasswordRetry(e){try{return await e()}catch(s){if(s instanceof m&&s.code===p.PASSWORD_WRONG)return h.warn("[CROSSx] 비밀번호 불일치 — 서버 검증 후 재시도"),await this.ensureVerifiedPassword("Incorrect password. Please enter your current password."),await e();throw s}}ensureInitialized(){if(!this.initialized)throw new m(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.passwordStore.clear(),this.initialized=!1,this.removeAllListeners(),It(null)}};se.OFFCHAIN_CHAIN_ID="0";let Fe=se;class rr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw h.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 h.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw h.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw h.error("Storage clear error:",e),e}}}const or="crossx-sdk",nr=1,Ae="data",He="keys",Lt="aes-primary",ir=12;class Dt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(or,nr);t.onupgradeneeded=()=>{const o=t.result;o.objectStoreNames.contains(Ae)||o.createObjectStore(Ae),o.objectStoreNames.contains(He)||o.createObjectStore(He)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,o)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>o(i.error)})}idbPut(e,s,t){return new Promise((o,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>o(),a.onerror=()=>n(a.error)})}idbDelete(e,s){return new Promise((t,o)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>o(i.error)})}idbClear(e){return new Promise((s,t)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).clear();n.onsuccess=()=>s(),n.onerror=()=>t(n.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(He,Lt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(He,Lt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(ir);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:o}}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),o=await this.encrypt(t);await this.idbPut(Ae,e,o)}catch(t){throw h.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Ae,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return h.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Ae,e)}catch(s){throw h.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Ae)}catch(e){throw h.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}new TextEncoder;const Mt=new TextDecoder,ar=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},cr=r=>{let e=r;e instanceof Uint8Array&&(e=Mt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return ar(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class z extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}z.code="ERR_JOSE_GENERIC";class lr extends z{constructor(e,s,t="unspecified",o="unspecified"){super(e,{cause:{claim:t,reason:o,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=o,this.payload=s}}lr.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class dr extends z{constructor(e,s,t="unspecified",o="unspecified"){super(e,{cause:{claim:t,reason:o,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=o,this.payload=s}}dr.code="ERR_JWT_EXPIRED";class ur extends z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}ur.code="ERR_JOSE_ALG_NOT_ALLOWED";class hr extends z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}hr.code="ERR_JOSE_NOT_SUPPORTED";class pr extends z{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}pr.code="ERR_JWE_DECRYPTION_FAILED";class fr extends z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}fr.code="ERR_JWE_INVALID";class _r extends z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}_r.code="ERR_JWS_INVALID";class ge extends z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ge.code="ERR_JWT_INVALID";class gr extends z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}gr.code="ERR_JWK_INVALID";class xr extends z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}xr.code="ERR_JWKS_INVALID";class wr extends z{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}wr.code="ERR_JWKS_NO_MATCHING_KEY";class mr extends z{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}mr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class yr extends z{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}yr.code="ERR_JWKS_TIMEOUT";class br extends z{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}br.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function vr(r){return typeof r=="object"&&r!==null}function Sr(r){if(!vr(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const Er=cr;function Ir(r){if(typeof r!="string")throw new ge("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new ge("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new ge("Invalid JWT");if(!e)throw new ge("JWTs must contain a payload");let t;try{t=Er(e)}catch{throw new ge("Failed to base64url decode the payload")}let o;try{o=JSON.parse(Mt.decode(t))}catch{throw new ge("Failed to parse the decoded payload as JSON")}if(!Sr(o))throw new ge("Invalid JWT Claims Set");return o}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ue(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function H(r,e,s=""){const t=rt(r),o=r==null?void 0:r.length,n=e!==void 0;if(!t||n&&o!==e){const i=s&&`"${s}" `,a=n?` of length ${e}`:"",c=t?`length=${o}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function $t(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ue(r.outputLen),ue(r.blockLen)}function Te(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 Bt(r,e){H(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 Ar(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Re(...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 ce(r,e){return r<<32-e|r>>>e}const Tr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Rr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Cr(r){for(let e=0;e<r.length;e++)r[e]=Rr(r[e]);return r}const Ut=Tr?r=>r:Cr,Ft=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Or=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Pe(r){if(H(r),Ft)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Or[r[s]];return e}const he={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ht(r){if(r>=he._0&&r<=he._9)return r-he._0;if(r>=he.A&&r<=he.F)return r-(he.A-10);if(r>=he.a&&r<=he.f)return r-(he.a-10)}function Ge(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ft)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 o=0,n=0;o<s;o++,n+=2){const i=Ht(r.charCodeAt(n)),a=Ht(r.charCodeAt(n+1));if(i===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}t[o]=i*16+a}return t}function xe(...r){let e=0;for(let t=0;t<r.length;t++){const o=r[t];H(o),e+=o.length}const s=new Uint8Array(e);for(let t=0,o=0;t<r.length;t++){const n=r[t];s.set(n,o),o+=n.length}return s}function Gt(r,e={}){const s=(o,n)=>r(n).update(o).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=o=>r(o),Object.assign(s,e),Object.freeze(s)}function Wt(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 kr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Pr(r,e,s){return r&e^~r&s}function Nr(r,e,s){return r&e^r&s^e&s}class Lr{constructor(e,s,t,o){S(this,"blockLen");S(this,"outputLen");S(this,"padOffset");S(this,"isLE");S(this,"buffer");S(this,"view");S(this,"finished",!1);S(this,"length",0);S(this,"pos",0);S(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=o,this.buffer=new Uint8Array(e),this.view=ot(this.buffer)}update(e){Te(this),H(e);const{view:s,buffer:t,blockLen:o}=this,n=e.length;for(let i=0;i<n;){const a=Math.min(o-this.pos,n-i);if(a===o){const c=ot(e);for(;o<=n-i;i+=o)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Te(this),Bt(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:o,isLE:n}=this;let{pos:i}=this;s[i++]=128,Re(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(t,0),i=0);for(let u=i;u<o;u++)s[u]=0;t.setBigUint64(o-8,BigInt(this.length*8),n),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,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],n)}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:o,finished:n,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=n,e.length=o,e.pos=a,o%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const we=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),We=BigInt(2**32-1),qt=BigInt(32);function Dr(r,e=!1){return e?{h:Number(r&We),l:Number(r>>qt&We)}:{h:Number(r>>qt&We)|0,l:Number(r&We)|0}}function Mr(r,e=!1){const s=r.length;let t=new Uint32Array(s),o=new Uint32Array(s);for(let n=0;n<s;n++){const{h:i,l:a}=Dr(r[n],e);[t[n],o[n]]=[i,a]}return[t,o]}const $r=(r,e,s)=>r<<s|e>>>32-s,Br=(r,e,s)=>e<<s|r>>>32-s,Ur=(r,e,s)=>e<<s-32|r>>>64-s,Fr=(r,e,s)=>r<<s-32|e>>>64-s,Hr=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]),me=new Uint32Array(64);class Gr extends Lr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:o,E:n,F:i,G:a,H:c}=this;return[e,s,t,o,n,i,a,c]}set(e,s,t,o,n,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)me[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const g=me[u-15],_=me[u-2],f=ce(g,7)^ce(g,18)^g>>>3,b=ce(_,17)^ce(_,19)^_>>>10;me[u]=b+me[u-7]+f+me[u-16]|0}let{A:t,B:o,C:n,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const g=ce(a,6)^ce(a,11)^ce(a,25),_=d+g+Pr(a,c,l)+Hr[u]+me[u]|0,b=(ce(t,2)^ce(t,13)^ce(t,22))+Nr(t,o,n)|0;d=l,l=c,c=a,a=i+_|0,i=n,n=o,o=t,t=_+b|0}t=t+this.A|0,o=o+this.B|0,n=n+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,o,n,i,a,c,l,d)}roundClean(){Re(me)}destroy(){this.set(0,0,0,0,0,0,0,0),Re(this.buffer)}}class Wr extends Gr{constructor(){super(32);S(this,"A",we[0]|0);S(this,"B",we[1]|0);S(this,"C",we[2]|0);S(this,"D",we[3]|0);S(this,"E",we[4]|0);S(this,"F",we[5]|0);S(this,"G",we[6]|0);S(this,"H",we[7]|0)}}const qr=Gt(()=>new Wr,kr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),it=BigInt(1);function qe(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Vt(r){if(typeof r=="bigint"){if(!je(r))throw new Error("positive bigint expected, got "+r)}else ue(r);return r}function Ve(r){const e=Vt(r).toString(16);return e.length&1?"0"+e:e}function Kt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?nt:BigInt("0x"+r)}function Ke(r){return Kt(Pe(r))}function jt(r){return Kt(Pe(Vr(H(r)).reverse()))}function at(r,e){ue(e),r=Vt(r);const s=Ge(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function zt(r,e){return at(r,e).reverse()}function Vr(r){return Uint8Array.from(r)}const je=r=>typeof r=="bigint"&&nt<=r;function Kr(r,e,s){return je(r)&&je(e)&&je(s)&&e<=r&&r<s}function jr(r,e,s,t){if(!Kr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function zr(r){let e;for(e=0;r>nt;r>>=it,e+=1);return e}const ct=r=>(it<<BigInt(r))-it;function Jr(r,e,s){if(ue(r,"hashLen"),ue(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),o=Uint8Array.of(),n=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const u=()=>{c.fill(1),l.fill(0),d=0},g=(...y)=>s(l,xe(c,...y)),_=(y=o)=>{l=g(n,y),c=g(),y.length!==0&&(l=g(i,y),c=g())},f=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const E=[];for(;y<e;){c=g();const D=c.slice();E.push(D),y+=c.length}return xe(...E)};return(y,E)=>{u(),_(y);let D;for(;!(D=E(f()));)_();return u(),D}}function lt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(n,i,a){const c=r[n];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${l}`)}const o=(n,i)=>Object.entries(n).forEach(([a,c])=>t(a,c,i));o(e,!1),o(s,!0)}function Jt(r){const e=new WeakMap;return(s,...t)=>{const o=e.get(s);if(o!==void 0)return o;const n=r(s,...t);return e.set(s,n),n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ee=BigInt(0),J=BigInt(1),Se=BigInt(2),Yt=BigInt(3),Zt=BigInt(4),Xt=BigInt(5),Yr=BigInt(7),Qt=BigInt(8),Zr=BigInt(9),es=BigInt(16);function ae(r,e){const s=r%e;return s>=ee?s:e+s}function ie(r,e,s){let t=r;for(;e-- >ee;)t*=t,t%=s;return t}function ts(r,e){if(r===ee)throw new Error("invert: expected non-zero number");if(e<=ee)throw new Error("invert: expected positive modulus, got "+e);let s=ae(r,e),t=e,o=ee,n=J;for(;s!==ee;){const a=t/s,c=t%s,l=o-n*a;t=s,s=c,o=n,n=l}if(t!==J)throw new Error("invert: does not exist");return ae(o,e)}function dt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function ss(r,e){const s=(r.ORDER+J)/Zt,t=r.pow(e,s);return dt(r,t,e),t}function Xr(r,e){const s=(r.ORDER-Xt)/Qt,t=r.mul(e,Se),o=r.pow(t,s),n=r.mul(e,o),i=r.mul(r.mul(n,Se),o),a=r.mul(n,r.sub(i,r.ONE));return dt(r,a,e),a}function Qr(r){const e=ze(r),s=rs(r),t=s(e,e.neg(e.ONE)),o=s(e,t),n=s(e,e.neg(t)),i=(r+Yr)/es;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const u=a.mul(l,o),g=a.mul(l,n),_=a.eql(a.sqr(d),c),f=a.eql(a.sqr(u),c);l=a.cmov(l,d,_),d=a.cmov(g,u,f);const b=a.eql(a.sqr(d),c),y=a.cmov(l,d,b);return dt(a,y,c),y}}function rs(r){if(r<Yt)throw new Error("sqrt is not defined for small field");let e=r-J,s=0;for(;e%Se===ee;)e/=Se,s++;let t=Se;const o=ze(r);for(;ns(o,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return ss;let n=o.pow(t,e);const i=(e+J)/Se;return function(c,l){if(c.is0(l))return l;if(ns(c,l)!==1)throw new Error("Cannot find square root");let d=s,u=c.mul(c.ONE,n),g=c.pow(l,e),_=c.pow(l,i);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let f=1,b=c.sqr(g);for(;!c.eql(b,c.ONE);)if(f++,b=c.sqr(b),f===d)throw new Error("Cannot find square root");const y=J<<BigInt(d-f-1),E=c.pow(u,y);d=f,u=c.sqr(E),g=c.mul(g,u),_=c.mul(_,E)}return _}}function eo(r){return r%Zt===Yt?ss:r%Qt===Xt?Xr:r%es===Zr?Qr(r):rs(r)}const to=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function so(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=to.reduce((t,o)=>(t[o]="function",t),e);return lt(r,s),r}function ro(r,e,s){if(s<ee)throw new Error("invalid exponent, negatives unsupported");if(s===ee)return r.ONE;if(s===J)return e;let t=r.ONE,o=e;for(;s>ee;)s&J&&(t=r.mul(t,o)),o=r.sqr(o),s>>=J;return t}function os(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),n=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),n),t}function ns(r,e){const s=(r.ORDER-J)/Se,t=r.pow(e,s),o=r.eql(t,r.ONE),n=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!o&&!n&&!i)throw new Error("invalid Legendre symbol result");return o?1:n?0:-1}function oo(r,e){e!==void 0&&ue(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class no{constructor(e,s={}){S(this,"ORDER");S(this,"BITS");S(this,"BYTES");S(this,"isLE");S(this,"ZERO",ee);S(this,"ONE",J);S(this,"_lengths");S(this,"_sqrt");S(this,"_mod");var i;if(e<=ee)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:o,nByteLength:n}=oo(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ae(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ee<=e&&e<this.ORDER}is0(e){return e===ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&J)===J}neg(e){return ae(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ae(e*e,this.ORDER)}add(e,s){return ae(e+s,this.ORDER)}sub(e,s){return ae(e-s,this.ORDER)}mul(e,s){return ae(e*s,this.ORDER)}pow(e,s){return ro(this,e,s)}div(e,s){return ae(e*ts(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 ts(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=eo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?zt(e,this.BYTES):at(e,this.BYTES)}fromBytes(e,s=!1){H(e);const{_lengths:t,BYTES:o,isLE:n,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=n?jt(e):Ke(e);if(a&&(c=ae(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 ze(r,e={}){return new no(r,e)}function is(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 as(r){const e=is(r);return e+Math.ceil(e/2)}function io(r,e,s=!1){H(r);const t=r.length,o=is(e),n=as(e);if(t<16||t<n||t>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+t);const i=s?jt(r):Ke(r),a=ae(i,e-J)+J;return s?zt(a,o):at(a,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ce=BigInt(0),Ee=BigInt(1);function Je(r,e){const s=e.negate();return r?s:e}function cs(r,e){const s=os(r.Fp,e.map(t=>t.Z));return e.map((t,o)=>r.fromAffine(t.toAffine(s[o])))}function ls(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function ut(r,e){ls(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),o=2**r,n=ct(r),i=BigInt(r);return{windows:s,windowSize:t,mask:n,maxNumber:o,shiftBy:i}}function ds(r,e,s){const{windowSize:t,mask:o,maxNumber:n,shiftBy:i}=s;let a=Number(r&o),c=r>>i;a>t&&(a-=n,c+=Ee);const l=e*t,d=l+Math.abs(a)-1,u=a===0,g=a<0,_=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:g,isNegF:_,offsetF:l}}const ht=new WeakMap,us=new WeakMap;function pt(r){return us.get(r)||1}function hs(r){if(r!==Ce)throw new Error("invalid wNAF")}class ao{constructor(e,s){S(this,"BASE");S(this,"ZERO");S(this,"Fn");S(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let o=e;for(;s>Ce;)s&Ee&&(t=t.add(o)),o=o.double(),s>>=Ee;return t}precomputeWindow(e,s){const{windows:t,windowSize:o}=ut(s,this.bits),n=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,n.push(a);for(let l=1;l<o;l++)a=a.add(i),n.push(a);i=a.double()}return n}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let o=this.ZERO,n=this.BASE;const i=ut(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:g,offsetF:_}=ds(t,a,i);t=c,d?n=n.add(Je(g,s[_])):o=o.add(Je(u,s[l]))}return hs(t),{p:o,f:n}}wNAFUnsafe(e,s,t,o=this.ZERO){const n=ut(e,this.bits);for(let i=0;i<n.windows&&t!==Ce;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=ds(t,i,n);if(t=a,!l){const u=s[c];o=o.add(d?u.negate():u)}}return hs(t),o}getPrecomputes(e,s,t){let o=ht.get(s);return o||(o=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(o=t(o)),ht.set(s,o))),o}cached(e,s,t){const o=pt(e);return this.wNAF(o,this.getPrecomputes(o,e,t),s)}unsafe(e,s,t,o){const n=pt(e);return n===1?this._unsafeLadder(e,s,o):this.wNAFUnsafe(n,this.getPrecomputes(n,e,t),s,o)}createCache(e,s){ls(s,this.bits),us.set(e,s),ht.delete(e)}hasCache(e){return pt(e)!==1}}function co(r,e,s,t){let o=e,n=r.ZERO,i=r.ZERO;for(;s>Ce||t>Ce;)s&Ee&&(n=n.add(o)),t&Ee&&(i=i.add(o)),o=o.double(),s>>=Ee,t>>=Ee;return{p1:n,p2:i}}function ps(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return so(e),e}else return ze(r,{isLE:s})}function lo(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>Ce))throw new Error(`CURVE.${c} must be positive bigint`)}const o=ps(e.p,s.Fp,t),n=ps(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!o.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:o,Fn:n}}function uo(r,e){return function(t){const o=r(t);return{secretKey:o,publicKey:e(o)}}}class fs{constructor(e,s){S(this,"oHash");S(this,"iHash");S(this,"blockLen");S(this,"outputLen");S(this,"finished",!1);S(this,"destroyed",!1);if($t(e),H(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,o=new Uint8Array(t);o.set(s.length>t?e.create().update(s).digest():s);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),Re(o)}update(e){return Te(this),this.iHash.update(e),this}digestInto(e){Te(this),H(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:o,destroyed:n,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=n,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 _s=(r,e,s)=>new fs(r,e).update(s).digest();_s.create=(r,e)=>new fs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gs=(r,e)=>(r+(r>=0?e:-e)/xs)/e;function ho(r,e,s){const[[t,o],[n,i]]=e,a=gs(i*r,s),c=gs(-o*r,s);let l=r-a*t-c*n,d=-a*o-c*i;const u=l<pe,g=d<pe;u&&(l=-l),g&&(d=-d);const _=ct(Math.ceil(zr(s)/2))+Oe;if(l<pe||l>=_||d<pe||d>=_)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:g,k2:d}}function ft(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function _t(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return qe(s.lowS,"lowS"),qe(s.prehash,"prehash"),s.format!==void 0&&ft(s.format),s}class po extends Error{constructor(e=""){super(e)}}const ye={Err:po,_tlv:{encode:(r,e)=>{const{Err:s}=ye;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,o=Ve(t);if(o.length/2&128)throw new s("tlv.encode: long form length too big");const n=t>127?Ve(o.length/2|128):"";return Ve(r)+n+o+e},decode(r,e){const{Err:s}=ye;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 o=e[t++],n=!!(o&128);let i=0;if(!n)i=o;else{const c=o&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 d of l)i=i<<8|d;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}=ye;if(r<pe)throw new e("integer: negative integers are not allowed");let s=Ve(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}=ye;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 Ke(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ye,o=H(r,void 0,"signature"),{v:n,l:i}=t.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,n),{v:l,l:d}=t.decode(2,c);if(d.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}=ye,t=e.encode(2,s.encode(r.r)),o=e.encode(2,s.encode(r.s)),n=t+o;return e.encode(48,n)}},pe=BigInt(0),Oe=BigInt(1),xs=BigInt(2),Ye=BigInt(3),fo=BigInt(4);function _o(r,e={}){const s=lo("weierstrass",r,e),{Fp:t,Fn:o}=s;let n=s.CURVE;const{h:i,n:a}=n;lt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(n.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ms(t,o);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,x,w){const{x:v,y:A}=x.toAffine(),C=t.toBytes(v);if(qe(w,"isCompressed"),w){d();const R=!t.isOdd(A);return xe(ws(R),C)}else return xe(Uint8Array.of(4),C,t.toBytes(A))}function g(L){H(L,void 0,"Point");const{publicKey:x,publicKeyUncompressed:w}=l,v=L.length,A=L[0],C=L.subarray(1);if(v===x&&(A===2||A===3)){const R=t.fromBytes(C);if(!t.isValid(R))throw new Error("bad point: is not on curve, wrong x");const O=b(R);let I;try{I=t.sqrt(O)}catch(q){const F=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}d();const k=t.isOdd(I);return(A&1)===1!==k&&(I=t.neg(I)),{x:R,y:I}}else if(v===w&&A===4){const R=t.BYTES,O=t.fromBytes(C.subarray(0,R)),I=t.fromBytes(C.subarray(R,R*2));if(!y(O,I))throw new Error("bad point: is not on curve");return{x:O,y:I}}else throw new Error(`bad point: got length ${v}, expected compressed=${x} or uncompressed=${w}`)}const _=e.toBytes||u,f=e.fromBytes||g;function b(L){const x=t.sqr(L),w=t.mul(x,L);return t.add(t.add(w,t.mul(L,n.a)),n.b)}function y(L,x){const w=t.sqr(x),v=b(L);return t.eql(w,v)}if(!y(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(n.a,Ye),fo),D=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(E,D)))throw new Error("bad curve params: a or b");function U(L,x,w=!1){if(!t.isValid(x)||w&&t.is0(x))throw new Error(`bad point coordinate ${L}`);return x}function M(L){if(!(L instanceof re))throw new Error("Weierstrass Point expected")}function B(L){if(!c||!c.basises)throw new Error("no endo");return ho(L,c.basises,o.ORDER)}const j=Jt((L,x)=>{const{X:w,Y:v,Z:A}=L;if(t.eql(A,t.ONE))return{x:w,y:v};const C=L.is0();x==null&&(x=C?t.ONE:t.inv(A));const R=t.mul(w,x),O=t.mul(v,x),I=t.mul(A,x);if(C)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:R,y:O}}),_e=Jt(L=>{if(L.is0()){if(e.allowInfinityPoint&&!t.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x,y:w}=L.toAffine();if(!t.isValid(x)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!y(x,w))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function be(L,x,w,v,A){return w=new re(t.mul(w.X,L),w.Y,w.Z),x=Je(v,x),w=Je(A,w),x.add(w)}const $=class ${constructor(x,w,v){S(this,"X");S(this,"Y");S(this,"Z");this.X=U("x",x),this.Y=U("y",w,!0),this.Z=U("z",v),Object.freeze(this)}static CURVE(){return n}static fromAffine(x){const{x:w,y:v}=x||{};if(!x||!t.isValid(w)||!t.isValid(v))throw new Error("invalid affine point");if(x instanceof $)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(v)?$.ZERO:new $(w,v,t.ONE)}static fromBytes(x){const w=$.fromAffine(f(H(x,void 0,"point")));return w.assertValidity(),w}static fromHex(x){return $.fromBytes(Ge(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,w=!0){return de.createCache(this,x),w||this.multiply(Ye),this}assertValidity(){_e(this)}hasEvenY(){const{y:x}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(x)}equals(x){M(x);const{X:w,Y:v,Z:A}=this,{X:C,Y:R,Z:O}=x,I=t.eql(t.mul(w,O),t.mul(C,A)),k=t.eql(t.mul(v,O),t.mul(R,A));return I&&k}negate(){return new $(this.X,t.neg(this.Y),this.Z)}double(){const{a:x,b:w}=n,v=t.mul(w,Ye),{X:A,Y:C,Z:R}=this;let O=t.ZERO,I=t.ZERO,k=t.ZERO,N=t.mul(A,A),q=t.mul(C,C),F=t.mul(R,R),P=t.mul(A,C);return P=t.add(P,P),k=t.mul(A,R),k=t.add(k,k),O=t.mul(x,k),I=t.mul(v,F),I=t.add(O,I),O=t.sub(q,I),I=t.add(q,I),I=t.mul(O,I),O=t.mul(P,O),k=t.mul(v,k),F=t.mul(x,F),P=t.sub(N,F),P=t.mul(x,P),P=t.add(P,k),k=t.add(N,N),N=t.add(k,N),N=t.add(N,F),N=t.mul(N,P),I=t.add(I,N),F=t.mul(C,R),F=t.add(F,F),N=t.mul(F,P),O=t.sub(O,N),k=t.mul(F,q),k=t.add(k,k),k=t.add(k,k),new $(O,I,k)}add(x){M(x);const{X:w,Y:v,Z:A}=this,{X:C,Y:R,Z:O}=x;let I=t.ZERO,k=t.ZERO,N=t.ZERO;const q=n.a,F=t.mul(n.b,Ye);let P=t.mul(w,C),V=t.mul(v,R),Z=t.mul(A,O),ne=t.add(w,v),G=t.add(C,R);ne=t.mul(ne,G),G=t.add(P,V),ne=t.sub(ne,G),G=t.add(w,A);let X=t.add(C,O);return G=t.mul(G,X),X=t.add(P,Z),G=t.sub(G,X),X=t.add(v,A),I=t.add(R,O),X=t.mul(X,I),I=t.add(V,Z),X=t.sub(X,I),N=t.mul(q,G),I=t.mul(F,Z),N=t.add(I,N),I=t.sub(V,N),N=t.add(V,N),k=t.mul(I,N),V=t.add(P,P),V=t.add(V,P),Z=t.mul(q,Z),G=t.mul(F,G),V=t.add(V,Z),Z=t.sub(P,Z),Z=t.mul(q,Z),G=t.add(G,Z),P=t.mul(V,G),k=t.add(k,P),P=t.mul(X,G),I=t.mul(ne,I),I=t.sub(I,P),P=t.mul(ne,V),N=t.mul(X,N),N=t.add(N,P),new $(I,k,N)}subtract(x){return this.add(x.negate())}is0(){return this.equals($.ZERO)}multiply(x){const{endo:w}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let v,A;const C=R=>de.cached(this,R,O=>cs($,O));if(w){const{k1neg:R,k1:O,k2neg:I,k2:k}=B(x),{p:N,f:q}=C(O),{p:F,f:P}=C(k);A=q.add(P),v=be(w.beta,N,F,R,I)}else{const{p:R,f:O}=C(x);v=R,A=O}return cs($,[v,A])[0]}multiplyUnsafe(x){const{endo:w}=e,v=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===pe||v.is0())return $.ZERO;if(x===Oe)return v;if(de.hasCache(this))return this.multiply(x);if(w){const{k1neg:A,k1:C,k2neg:R,k2:O}=B(x),{p1:I,p2:k}=co($,v,C,O);return be(w.beta,I,k,A,R)}else return de.unsafe(v,x)}toAffine(x){return j(this,x)}isTorsionFree(){const{isTorsionFree:x}=e;return i===Oe?!0:x?x($,this):de.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=e;return i===Oe?this:x?x($,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return qe(x,"isCompressed"),this.assertValidity(),_($,this,x)}toHex(x=!0){return Pe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};S($,"BASE",new $(n.Gx,n.Gy,t.ONE)),S($,"ZERO",new $(t.ZERO,t.ONE,t.ZERO)),S($,"Fp",t),S($,"Fn",o);let re=$;const Ie=o.BITS,de=new ao(re,e.endo?Math.ceil(Ie/2):Ie);return re.BASE.precompute(8),re}function ws(r){return Uint8Array.of(r?2:3)}function ms(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function go(r,e={}){const{Fn:s}=r,t=e.randomBytes||Wt,o=Object.assign(ms(r.Fp,s),{seed:as(s.ORDER)});function n(_){try{const f=s.fromBytes(_);return s.isValidNot0(f)}catch{return!1}}function i(_,f){const{publicKey:b,publicKeyUncompressed:y}=o;try{const E=_.length;return f===!0&&E!==b||f===!1&&E!==y?!1:!!r.fromBytes(_)}catch{return!1}}function a(_=t(o.seed)){return io(H(_,o.seed,"seed"),s.ORDER)}function c(_,f=!0){return r.BASE.multiply(s.fromBytes(_)).toBytes(f)}function l(_){const{secretKey:f,publicKey:b,publicKeyUncompressed:y}=o;if(!rt(_)||"_lengths"in s&&s._lengths||f===b)return;const E=H(_,void 0,"key").length;return E===b||E===y}function d(_,f,b=!0){if(l(_)===!0)throw new Error("first arg must be private key");if(l(f)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(_);return r.fromBytes(f).multiply(y).toBytes(b)}const u={isValidSecretKey:n,isValidPublicKey:i,randomSecretKey:a},g=uo(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:g,Point:r,utils:u,lengths:o})}function xo(r,e,s={}){$t(e),lt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Wt,o=s.hmac||((x,w)=>_s(e,x,w)),{Fp:n,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:g,lengths:_}=go(r,s),f={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*xs<n.ORDER;function y(x){const w=a>>Oe;return x>w}function E(x,w){if(!i.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function D(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(x,w){ft(w);const v=_.signature,A=w==="compact"?v:w==="recovered"?v+1:void 0;return H(x,A)}class M{constructor(w,v,A){S(this,"r");S(this,"s");S(this,"recovery");if(this.r=E("r",w),this.s=E("s",v),A!=null){if(D(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(w,v=f.format){U(w,v);let A;if(v==="der"){const{r:I,s:k}=ye.toSig(H(w));return new M(I,k)}v==="recovered"&&(A=w[0],v="compact",w=w.subarray(1));const C=_.signature/2,R=w.subarray(0,C),O=w.subarray(C,C*2);return new M(i.fromBytes(R),i.fromBytes(O),A)}static fromHex(w,v){return this.fromBytes(Ge(w),v)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new M(this.r,this.s,w)}recoverPublicKey(w){const{r:v,s:A}=this,C=this.assertRecovery(),R=C===2||C===3?v+a:v;if(!n.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const O=n.toBytes(R),I=r.fromBytes(xe(ws((C&1)===0),O)),k=i.inv(R),N=j(H(w,void 0,"msgHash")),q=i.create(-N*k),F=i.create(A*k),P=r.BASE.multiplyUnsafe(q).add(I.multiplyUnsafe(F));if(P.is0())throw new Error("invalid recovery: point at infinify");return P.assertValidity(),P}hasHighS(){return y(this.s)}toBytes(w=f.format){if(ft(w),w==="der")return Ge(ye.hexFromSig(this));const{r:v,s:A}=this,C=i.toBytes(v),R=i.toBytes(A);return w==="recovered"?(D(),xe(Uint8Array.of(this.assertRecovery()),C,R)):xe(C,R)}toHex(w){return Pe(this.toBytes(w))}}const B=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const v=Ke(w),A=w.length*8-c;return A>0?v>>BigInt(A):v},j=s.bits2int_modN||function(w){return i.create(B(w))},_e=ct(c);function be(x){return jr("num < 2^"+c,x,pe,_e),i.toBytes(x)}function re(x,w){return H(x,void 0,"message"),w?H(e(x),void 0,"prehashed message"):x}function Ie(x,w,v){const{lowS:A,prehash:C,extraEntropy:R}=_t(v,f);x=re(x,C);const O=j(x),I=i.fromBytes(w);if(!i.isValidNot0(I))throw new Error("invalid private key");const k=[be(I),be(O)];if(R!=null&&R!==!1){const P=R===!0?t(_.secretKey):R;k.push(H(P,void 0,"extraEntropy"))}const N=xe(...k),q=O;function F(P){const V=B(P);if(!i.isValidNot0(V))return;const Z=i.inv(V),ne=r.BASE.multiply(V).toAffine(),G=i.create(ne.x);if(G===pe)return;const X=i.create(Z*i.create(q+G*I));if(X===pe)return;let Ls=(ne.x===G?0:2)|Number(ne.y&Oe),Ds=X;return A&&y(X)&&(Ds=i.neg(X),Ls^=1),new M(G,Ds,b?void 0:Ls)}return{seed:N,k2sig:F}}function de(x,w,v={}){const{seed:A,k2sig:C}=Ie(x,w,v);return Jr(e.outputLen,i.BYTES,o)(A,C).toBytes(v.format)}function $(x,w,v,A={}){const{lowS:C,prehash:R,format:O}=_t(A,f);if(v=H(v,void 0,"publicKey"),w=re(w,R),!rt(x)){const I=x instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+I)}U(x,O);try{const I=M.fromBytes(x,O),k=r.fromBytes(v);if(C&&I.hasHighS())return!1;const{r:N,s:q}=I,F=j(w),P=i.inv(q),V=i.create(F*P),Z=i.create(N*P),ne=r.BASE.multiplyUnsafe(V).add(k.multiplyUnsafe(Z));return ne.is0()?!1:i.create(ne.x)===N}catch{return!1}}function L(x,w,v={}){const{prehash:A}=_t(v,f);return w=re(w,A),M.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:g,lengths:_,Point:r,sign:de,verify:$,recoverPublicKey:L,Signature:M,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},wo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ys=BigInt(2);function mo(r){const e=gt.p,s=BigInt(3),t=BigInt(6),o=BigInt(11),n=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=ie(d,s,e)*d%e,g=ie(u,s,e)*d%e,_=ie(g,ys,e)*l%e,f=ie(_,o,e)*_%e,b=ie(f,n,e)*f%e,y=ie(b,a,e)*b%e,E=ie(y,c,e)*y%e,D=ie(E,a,e)*b%e,U=ie(D,s,e)*d%e,M=ie(U,i,e)*f%e,B=ie(M,t,e)*l%e,j=ie(B,ys,e);if(!xt.eql(xt.sqr(j),r))throw new Error("Cannot find square root");return j}const xt=ze(gt.p,{sqrt:mo}),yo=xo(_o(gt,{Fp:xt,endo:wo}),qr),bo=BigInt(0),Ne=BigInt(1),vo=BigInt(2),So=BigInt(7),Eo=BigInt(256),Io=BigInt(113),bs=[],vs=[],Ss=[];for(let r=0,e=Ne,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],bs.push(2*(5*t+s)),vs.push((r+1)*(r+2)/2%64);let o=bo;for(let n=0;n<7;n++)e=(e<<Ne^(e>>So)*Io)%Eo,e&vo&&(o^=Ne<<(Ne<<BigInt(n))-Ne);Ss.push(o)}const Es=Mr(Ss,!0),Ao=Es[0],To=Es[1],Is=(r,e,s)=>s>32?Ur(r,e,s):$r(r,e,s),As=(r,e,s)=>s>32?Fr(r,e,s):Br(r,e,s);function Ro(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],d=s[c+1],u=Is(l,d,1)^s[a],g=As(l,d,1)^s[a+1];for(let _=0;_<50;_+=10)r[i+_]^=u,r[i+_+1]^=g}let o=r[2],n=r[3];for(let i=0;i<24;i++){const a=vs[i],c=Is(o,n,a),l=As(o,n,a),d=bs[i];o=r[d],n=r[d+1],r[d]=c,r[d+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]^=Ao[t],r[1]^=To[t]}Re(s)}class wt{constructor(e,s,t,o=!1,n=24){S(this,"state");S(this,"pos",0);S(this,"posOut",0);S(this,"finished",!1);S(this,"state32");S(this,"destroyed",!1);S(this,"blockLen");S(this,"suffix");S(this,"outputLen");S(this,"enableXOF",!1);S(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=o,this.rounds=n,ue(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ar(this.state)}clone(){return this._cloneInto()}keccak(){Ut(this.state32),Ro(this.state32,this.rounds),Ut(this.state32),this.posOut=0,this.pos=0}update(e){Te(this),H(e);const{blockLen:s,state:t}=this,o=e.length;for(let n=0;n<o;){const i=Math.min(s-this.pos,o-n);for(let a=0;a<i;a++)t[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:o}=this;e[t]^=s,s&128&&t===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){Te(this,!1),H(e),this.finish();const s=this.state,{blockLen:t}=this;for(let o=0,n=e.length;o<n;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,n-o);e.set(s.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=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 ue(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Bt(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,Re(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:o,rounds:n,enableXOF:i}=this;return e||(e=new wt(s,t,o,i,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=t,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Ts=((r,e,s,t={})=>Gt(()=>new wt(e,r,s),t))(1,136,32);class Co{async verifyJWT(e,s){try{const t=this.decodeJWT(e);h.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const o=Math.floor(Date.now()/1e3);return t.exp&&t.exp<o?(h.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:o,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(h.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(h.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw h.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ir(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),o=new TextEncoder().encode(`Ethereum Signed Message:
2
- ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);const i=Ts(n),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Oo(a),l=c.slice(0,32),d=c.slice(32,64),u=c[64],g=u>=27?u-27:u,b=new yo.Signature(Rs(l),Rs(d)).addRecoveryBit(g).recoverPublicKey(i).toBytes(!1).slice(1),y=Ts(b);return"0x"+Pe(y.slice(12))}}function Oo(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 ko=3e4;class Po{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??ko);try{const o=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 n;const i=await o.text();try{n=i?JSON.parse(i):null}catch{n={_raw:i}}return{status:o.status,data:n,headers:Object.fromEntries(o.headers.entries())}}finally{clearTimeout(t)}}}class mt{static generateState(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}openAuth(e){return new Promise((s,t)=>{const o=Math.max(e.width??500,500),n=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-o)/2,a=window.screenY+(window.outerHeight-n)/2,c=mt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,u=window.open(d,"CROSSx OAuth",`width=${o},height=${n},left=${i},top=${a}`);if(!u){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const g=setTimeout(()=>{h.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),U(),t(new Error("Authentication timeout"))},5*60*1e3),_=10,f=30;let b=0,y=null;const E=()=>{clearInterval(D),h.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+f+"초간 대기합니다"),y=setTimeout(()=>{U(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},f*1e3)},D=setInterval(()=>{b++;try{u.closed&&(b<=_?E():(U(),t(new Error("로그인이 취소되었습니다"))))}catch{E()}},1e3),U=()=>{clearTimeout(g),clearInterval(D),y&&clearTimeout(y),window.removeEventListener("message",M)},M=B=>{var _e,be,re,Ie,de,$,L;if(B.origin!==e.expectedOrigin)return;U(),h.log("[CROSSx] OAuth postMessage 수신 — status:",B.data.status);const j=B.data.state??((_e=B.data.data)==null?void 0:_e.state);if(!j||j!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(B.data.status==="success"){const x=((be=B.data.data)==null?void 0:be.accessToken)||((re=B.data.data)==null?void 0:re.idToken);h.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((Ie=B.data.data)!=null&&Ie.accessToken),hasIdToken:!!((de=B.data.data)!=null&&de.idToken)}),x?s(x):(h.error("[CROSSx] 토큰을 찾을 수 없음:",B.data),t(new Error("Token not found in response")))}else h.error("[CROSSx] OAuth 실패:",($=B.data.data)==null?void 0:$.error),t(new Error(((L=B.data.data)==null?void 0:L.error)||"Authentication failed"))};window.addEventListener("message",M)})}}const Le="crossx_wallet_data",ke="crossx_mock_pw_hash";class No{constructor(e,s){this.storage=e,this.passwordStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return h.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Le)?"exists":"not_found";return h.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Le);if(t)return t;const o={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Le,o);const n=(s=this.passwordStore)==null?void 0:s.get();return n&&(await this.storage.set(ke,n),h.log("[Mock] 지갑 생성 — 비밀번호 저장됨")),o}catch(t){throw new m(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Le);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 h.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,o=0,n,i){return h.log(`[Mock] signMessage chainId=${s} index=${o} uuid=${n} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,o=0,n,i){return h.log(`[Mock] signTypedData chainId=${s} index=${o} uuid=${n} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,o=0,n){h.log(`[Mock] signTransaction chainId=${s} index=${o} uuid=${n}:`,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,o){return h.log(`[Mock] sendTransaction chainId=${s} uuid=${o}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPassword(e){var t;if(h.log("[Mock] verifyPassword"),this.passwordScenario==="wrong")return!1;const s=await this.storage.get(ke);return s&&s!==e?!1:(s||await this.storage.set(ke,e),(t=this.passwordStore)==null||t.set(e),h.log("[Mock] verifyPassword → 성공"),!0)}async changePassword(e,s){var n;if(h.log("[Mock] changePassword"),this.passwordScenario==="wrong")throw new m(p.PASSWORD_WRONG,"Incorrect password.");const t=(n=this.passwordStore)==null?void 0:n.get(),o=await this.storage.get(ke);if(o&&t&&o!==t)throw new m(p.PASSWORD_WRONG,"Incorrect password.");await this.storage.set(ke,s),h.log("[Mock] changePassword 완료")}async migrateWallet(e,s){var n;if(h.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new m(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new m(p.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(Le,t);const o=(n=this.passwordStore)==null?void 0:n.get();return o&&(await this.storage.set(ke,o),h.log("[Mock] 마이그레이션 — 비밀번호 저장됨")),t}async getShareC(){return h.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyPin(e,s){return h.log("[Mock] verifyPin"),{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 Ze{constructor(e,s,t,o,n){this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=o,this.passwordStore=n??null}getPassword(){var e;return((e=this.passwordStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new m(p.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const o=this.getAuthToken(),n=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:n,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const u=d.message||d.data||"API 요청에 실패했습니다";h.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:u,url:n,method:e,fullResponse:d});const g=Ze.mapGatewayError(d.code,d.data),_=Ze.getGatewayErrorMessage(d.code,u),f=new m(g,_,d.data??void 0);throw f.gatewayCode=d.code,f.gatewayMessage=u,f}return h.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:n,method:e}),d.data??d}return d}catch(l){if(l instanceof m)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,u=d.message||d.data||"API 요청에 실패했습니다",g=d.code||"UNKNOWN";throw h.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:g,message:u,url:n,method:e,status:(c=l.response)==null?void 0:c.status}),new m(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${g}): ${u}`)}throw l}}async checkWallet(){h.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return h.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,h.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(h.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw h.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new m(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){h.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const n=await this.getAddress(e,0);return h.log("[CROSSx] 주소 조회 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}h.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePassword()},o=await this.request("POST","/mnemonic/create",t);return h.log("[CROSSx] /mnemonic/create 완료 — address:",o.address),{id:e,address:o.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.requirePassword(),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 m(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new m(p.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 m(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const o={action:e,params:t},n=await this.request("POST","/mnemonic/prepare",o);return{uuid:n.uuid,expiresAt:n.expiresAt}}async signMessage(e,s,t,o,n,i){const a={message:t};n&&(a.uuid=n),i&&(a.from=i);const c=this.getPassword();c&&(a.password=c);const l=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:l.signature,format:"hex"}}async signTypedData(e,s,t,o,n,i){const a={typedData:t};n&&(a.uuid=n),i&&(a.from=i);const c=this.getPassword();c&&(a.password=c);const l=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:l.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,o,n){const i={unsignedTx:this.buildUnsignedTx(t)};n&&(i.uuid=n);const a=this.getPassword();a&&(i.password=a);const c=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:c.signedTx,txHash:c.txHash,format:"hex"}}async sendTransaction(e,s,t,o){const n={unsignedTx:this.buildUnsignedTx(t)};o&&(n.uuid=o);const i=this.getPassword();return i&&(n.password=i),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,n)).txHash}}async migrateWallet(e,s){h.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={pin:e,sub:s,password:this.requirePassword()},o=await this.request("POST","/mnemonic/migrate",t);return h.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",o.address),{id:s,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePassword()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPassword(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).verified}async changePassword(e,s){const t={password:this.requirePassword(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePassword()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyPin(e,s){const t={pin:e,sub:s};return this.request("POST","/mnemonic/verify-pin",t)}requirePassword(){const e=this.getPassword();if(!e)throw new m(p.PASSWORD_NOT_SET,"비밀번호가 설정되지 않았습니다. 비밀번호를 입력해 주세요.");return e}static mapGatewayError(e,s){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10028:return p.PASSWORD_WRONG;case-10029:return p.PASSWORD_COMPLEXITY;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";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 is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10028:return"Incorrect password. Please try again.";case-10029:return"Password does not meet complexity requirements. Please use a stronger password.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";default:return`Request failed (${e}): ${s}`}}}class De{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=De.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(o=>o.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?sr:tr;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 m(De.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=De.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new m(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Me).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const Cs="__crossx-confirm-style",K="__crossx-confirm-overlay",Lo={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=Lo[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 Do=`
1
+ var CROSSx=function(ne){"use strict";var xo=Object.defineProperty;var mo=(ne,p,f)=>p in ne?xo(ne,p,{enumerable:!0,configurable:!0,writable:!0,value:f}):ne[p]=f;var E=(ne,p,f)=>mo(ne,typeof p!="symbol"?p+"":p,f);var p=(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.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",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_CANCELLED="PIN_CANCELLED",r.PIN_LOCKED="PIN_LOCKED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class f extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,f.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const He={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}},$s=Object.fromEntries(Object.entries(He).map(([r,e])=>[r,e.caipId])),Bs=new Map(Object.values(He).map(r=>[r.caipId,r]));new Map(Object.values(He).map(r=>[r.chainId,r]));const Us={symbol:"",decimals:18};function tt(r){var e;return((e=Bs.get(r))==null?void 0:e.nativeCurrency)??Us}class St{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 f(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new f(p.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 Ee=null;function wo(r){}function Et(r){Ee=r}const u={log(...r){if(Ee){Ee.log(...r);return}},warn(...r){if(Ee){Ee.warn(...r);return}},error(...r){if(Ee){Ee.error(...r);return}}},Hs={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로 계속하기",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:"이용 가능 시간"},It={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",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"},Fs={ko:Hs,en:It};function Tt(r="en",e){return Fs[r]??It}const Fe="crossx_access_token",Ce="crossx_refresh_token",Le="crossx_user_info";class Ws{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}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new f(p.AUTH_FAILED,`${s} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new f(p.AUTH_FAILED,`${s} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:h}=this.config,m=`${d}${l}`;u.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const x=await this.oauth.openAuth({authUrl:m,expectedOrigin:new URL(d).origin});u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",x.length,")");const{accessToken:w,refreshToken:I}=await this.exchangeFirebaseToken(x,h);let y,S;try{const U=this.crypto.decodeJWT(x);S=(n=U.firebase)==null?void 0:n.sign_in_provider;const v=((o=U.firebase)==null?void 0:o.identities)??{};S==="google.com"?y=(i=v["google.com"])==null?void 0:i[0]:S==="apple.com"&&(y=(a=v["apple.com"])==null?void 0:a[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",S,"hasProviderSub:",!!y)}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const U=this.crypto.decodeJWT(w);u.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const v=await this.crypto.verifyJWT(w);if(t=v.signatureVerified??!1,!v.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const P=v.payload;s={id:P.sub,email:P.email,signInProvider:S,providerSub:y},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set(Fe,w),I&&await this.storage.set(Ce,I))}else{const U=this.crypto.decodeJWT(x);s={id:U.sub,email:U.email,signInProvider:S,providerSub:y},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}u.log("[CROSSx] 사용자 정보 — id:",s.id);const C=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Le,C),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return u.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.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"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new f(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.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{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Le);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Fe),n=await this.storage.get(Ce);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Le);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return u.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ce),await this.storage.remove(Le),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),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"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new f(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(Fe,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ce,l)}return u.log("[CROSSx] silentRefresh 성공"),c}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 u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.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 u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;u.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(Fe,e),s&&await this.storage.set(Ce,s)),await this.storage.set(Le,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return u.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",o),o==="migration_required")u.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,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof f&&o.code===p.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof f&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Gs="crossx_access_token",qs="crossx_refresh_token",Vs="crossx_user_info";class Ks{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(Gs),await this.storage.remove(qs)),await this.storage.remove(Vs)}}class Js{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new f(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class At{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 zs{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},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 f(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class js{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 We={production:{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"},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 Ys(r){const e=r.environment;return e&&e in We?We[e]:null}function Xs(){try{if(typeof window.__CROSSX_CONFIG__<"u"){const r=typeof window.__CROSSX_CONFIG__=="string"?JSON.parse(window.__CROSSX_CONFIG__):window.__CROSSX_CONFIG__,e=Ys(r);if(e)return e}}catch{}return We.production}const Zs=2e3,Rt=6e4,Qs=1e3,er=1e4,tr="0x77359400",Pt="0x3B9ACA00",kt=130,Nt=6,Ot=18,sr=0,rr=30*1e3,ie=class ie extends js{constructor(e,s,t,n,o,i,a,c,l,d,h){var m;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._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Et(e.logger),this.confirmation=l,this.pinStore=h??new At,this.chainRegistry=d,this.jsonRpc=new zs(d,o),this.signInUseCase=new Ws(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ks(this.internalConfig,t,c),this.migrateWalletUseCase=new Js(t,a),(m=a.setOnUnauthorized)==null||m.call(a,()=>this.forceLogout())}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){console.log("[CROSSx SDK] v1.2.0 초기화 중..."),this.confirmation.setMessages(Tt(this._config.locale));try{const s=Xs();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl;const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){this.applyAuthResult(t);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(n){if(!(n instanceof f&&n.code===p.PIN_CANCELLED))throw n;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(t!=null&&t.success)}),t??null}catch(s){throw new f(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new f(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new f(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}catch(t){throw t instanceof f&&t.code===p.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new f(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new f(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new f(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}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 f&&s.code===p.PIN_CANCELLED||u.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 f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof f?s:new f(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.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 f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await 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.walletProvider.getAddress(this.userId,n))).address,index:n};return s.push(i),i},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof f?e:new f(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof f?s:new f(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}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(Tt(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new f(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof f&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new f(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof f&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new f(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePinForSigning();const n=await this.resolveAddress(t==null?void 0:t.index);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new f(p.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const a=await this.withPinRetry(()=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address));return this.verifySignatureSigner(s,a.signature,n.address),{chainId:e,signature:a.signature,message:s,address:n.address}}catch(a){throw a instanceof f?a:new f(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,a)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new f(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");await this.ensurePinForSigning(),ie.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new f(p.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const a=await this.withPinRetry(()=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address));return ie.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof f?a:new f(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(ie.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePinForSigning();const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign",{tx:n})).uuid);const i=tt(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:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new f(p.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const c=await this.withPinRetry(()=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o));return ie.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof f)throw c;const l=c instanceof Error?c.message:String(c);throw new f(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePinForSigning();const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("send",{tx:n})).uuid);const i=tt(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:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new f(p.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const c=await this.withPinRetry(async()=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,o)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);return l.txHash??l.signature});return{chainId:e,txHash:c,status:"pending"}}catch(c){if(c instanceof f)throw c;const l=c instanceof Error?c.message:String(c);throw new f(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${l}`,c)}}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??Qs,o=er,i=t.timeoutMs??Rt,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(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new f(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var I,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((I=this._config.receiptPolling)==null?void 0:I.intervalMs)??Zs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??Rt,d=tt(e),h=s.from??"";let m,x;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{m=S;const C=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),U=s.value?BigInt(s.value):0n,v=ie.formatTxAmount(s.value,d.symbol,d.decimals),P=ie.formatTxAmount("0x"+C.toString(16),d.symbol,d.decimals),N=ie.formatTxAmount("0x"+(U+C).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:S.from,to:S.to??s.to,amount:v,fees:P,total:N,nativeSymbol:d.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(x=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:h,to:s.to,amount:ie.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:s.to},w),x)throw x;return{chainId:e,txHash:a,receipt:m}}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 f(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof f?n:new f(p.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 f(p.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 f(p.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 f(p.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 f(p.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 f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(p.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:ie.formatWei(n),chainId:e}}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(p.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(Ot),n=s/t,i=(s%t).toString().padStart(Ot,"0").replace(/0+$/,"").slice(0,Nt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new St(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof f)throw n;const o=n instanceof Error?n.message:String(n);throw new f(p.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,Nt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0,o=5,i=null;for(;;){n++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:t,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(l===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${l.length}자리) — verify-recovery-pin API 호출`),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyRecoveryPin)==null?void 0:c.call(a,l,e));if(!d){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const h=d.pinStatus;if(o=h.maxAttempts,n=o-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const m=h.lockExpiresAt*1e3,x=Math.max(1,Math.round((m-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${x}초, 메시지: ${w}`),await this.confirmation.showRecoveryPinLockedPrompt(x,w),n=0,t="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),t="Incorrect PIN."}catch(d){if(!(d instanceof f))throw d;if(d.code===p.MIGRATION_PIN_LOCKED){const h=d.details;if(o=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.permanent)===!0)return u.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 m=((h==null?void 0:h.lockExpiresAt)??0)*1e3,x=Math.max(1,Math.round((m-Date.now())/1e3)),w=x<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${x}초`),await this.confirmation.showRecoveryPinLockedPrompt(x,w),n=0,t="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",d),d}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const l=await this.migrateWalletUseCase.execute(i,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof f&&l.code===p.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.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};if(n){const l=c.from??this.address;if(l){u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=Pt;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=tr,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Pt,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=ie.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new f(p.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 f(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new f(p.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 f(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==kt)throw new f(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${kt} 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 f(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new f(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new f(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof f)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}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=ie.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,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.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}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 f(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),u.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 f(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s});if(!i)throw new f(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}if(!await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof f){if(c.code===p.PIN_WRONG)return{ok:!1,error:"Incorrect PIN. Please try again."};if(c.code===p.PIN_LOCKED)return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:(a=c.details)==null?void 0:a.lockExpiresAt}}throw c}}}))throw new f(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");t()}catch(o){throw n(o),o}finally{this._verifyPinMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let s,t;try{return await e()}catch(n){if(n instanceof f)if(n.code===p.PIN_WRONG)s="Incorrect PIN. Please enter your current PIN.";else if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked."}else throw n;else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",s),this.pinStore.clear(),await this.ensureVerifiedPin(s,t),t=void 0;try{return await e()}catch(n){if(n instanceof f){if(n.code===p.PIN_WRONG){s="Incorrect PIN. Please try again.";continue}if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked.";continue}}throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new f(p.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 f(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new f(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Et(null)}};ie.OFFCHAIN_CHAIN_ID="0";let Ge=ie;class nr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.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 u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const or="crossx-sdk",ir=1,Ae="data",qe="keys",Ct="aes-primary",ar=12;class Lt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(or,ir);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Ae)||n.createObjectStore(Ae),n.objectStoreNames.contains(qe)||n.createObjectStore(qe)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.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(qe,Ct);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(qe,Ct,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(ar);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(Ae,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Ae,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Ae,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Ae)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}new TextEncoder;const Dt=new TextDecoder,cr=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},lr=r=>{let e=r;e instanceof Uint8Array&&(e=Dt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return cr(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Z extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Z.code="ERR_JOSE_GENERIC";class dr extends Z{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}dr.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class ur extends Z{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}ur.code="ERR_JWT_EXPIRED";class hr extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}hr.code="ERR_JOSE_ALG_NOT_ALLOWED";class pr extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}pr.code="ERR_JOSE_NOT_SUPPORTED";class fr extends Z{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}fr.code="ERR_JWE_DECRYPTION_FAILED";class _r extends Z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}_r.code="ERR_JWE_INVALID";class gr extends Z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}gr.code="ERR_JWS_INVALID";class me extends Z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}me.code="ERR_JWT_INVALID";class xr extends Z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}xr.code="ERR_JWK_INVALID";class mr extends Z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}mr.code="ERR_JWKS_INVALID";class wr extends Z{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}wr.code="ERR_JWKS_NO_MATCHING_KEY";class yr extends Z{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}yr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class br extends Z{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}br.code="ERR_JWKS_TIMEOUT";class vr extends Z{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}vr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function Sr(r){return typeof r=="object"&&r!==null}function Er(r){if(!Sr(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const Ir=lr;function Tr(r){if(typeof r!="string")throw new me("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new me("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new me("Invalid JWT");if(!e)throw new me("JWTs must contain a payload");let t;try{t=Ir(e)}catch{throw new me("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Dt.decode(t))}catch{throw new me("Failed to parse the decoded payload as JSON")}if(!Er(n))throw new me("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function st(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function fe(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function K(r,e,s=""){const t=st(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 Mt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");fe(r.outputLen),fe(r.blockLen)}function Re(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 $t(r,e){K(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 Ar(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Pe(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function rt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function he(r,e){return r<<32-e|r>>>e}const Rr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Pr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function kr(r){for(let e=0;e<r.length;e++)r[e]=Pr(r[e]);return r}const Bt=Rr?r=>r:kr,Ut=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Nr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function De(r){if(K(r),Ut)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Nr[r[s]];return e}const _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ht(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 Ve(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ut)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=Ht(r.charCodeAt(o)),a=Ht(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 we(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];K(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 Ft(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 Wt(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 Or=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Cr(r,e,s){return r&e^~r&s}function Lr(r,e,s){return r&e^r&s^e&s}class Dr{constructor(e,s,t,n){E(this,"blockLen");E(this,"outputLen");E(this,"padOffset");E(this,"isLE");E(this,"buffer");E(this,"view");E(this,"finished",!1);E(this,"length",0);E(this,"pos",0);E(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=rt(this.buffer)}update(e){Re(this),K(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=rt(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){Re(this),$t(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Pe(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let h=i;h<n;h++)s[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=rt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],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]),Ke=BigInt(2**32-1),Gt=BigInt(32);function Mr(r,e=!1){return e?{h:Number(r&Ke),l:Number(r>>Gt&Ke)}:{h:Number(r>>Gt&Ke)|0,l:Number(r&Ke)|0}}function $r(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}=Mr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const Br=(r,e,s)=>r<<s|e>>>32-s,Ur=(r,e,s)=>e<<s|r>>>32-s,Hr=(r,e,s)=>e<<s-32|r>>>64-s,Fr=(r,e,s)=>r<<s-32|e>>>64-s,Wr=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 Gr extends Dr{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 h=0;h<16;h++,s+=4)be[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const m=be[h-15],x=be[h-2],w=he(m,7)^he(m,18)^m>>>3,I=he(x,17)^he(x,19)^x>>>10;be[h]=I+be[h-7]+w+be[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){const m=he(a,6)^he(a,11)^he(a,25),x=d+m+Cr(a,c,l)+Wr[h]+be[h]|0,I=(he(t,2)^he(t,13)^he(t,22))+Lr(t,n,o)|0;d=l,l=c,c=a,a=i+x|0,i=o,o=n,n=t,t=x+I|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,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){Pe(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Pe(this.buffer)}}class qr extends Gr{constructor(){super(32);E(this,"A",ye[0]|0);E(this,"B",ye[1]|0);E(this,"C",ye[2]|0);E(this,"D",ye[3]|0);E(this,"E",ye[4]|0);E(this,"F",ye[5]|0);E(this,"G",ye[6]|0);E(this,"H",ye[7]|0)}}const Vr=Ft(()=>new qr,Or(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),ot=BigInt(1);function Je(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function qt(r){if(typeof r=="bigint"){if(!Ye(r))throw new Error("positive bigint expected, got "+r)}else fe(r);return r}function ze(r){const e=qt(r).toString(16);return e.length&1?"0"+e:e}function Vt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?nt:BigInt("0x"+r)}function je(r){return Vt(De(r))}function Kt(r){return Vt(De(Kr(K(r)).reverse()))}function it(r,e){fe(e),r=qt(r);const s=Ve(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function Jt(r,e){return it(r,e).reverse()}function Kr(r){return Uint8Array.from(r)}const Ye=r=>typeof r=="bigint"&&nt<=r;function Jr(r,e,s){return Ye(r)&&Ye(e)&&Ye(s)&&e<=r&&r<s}function zr(r,e,s,t){if(!Jr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function jr(r){let e;for(e=0;r>nt;r>>=ot,e+=1);return e}const at=r=>(ot<<BigInt(r))-ot;function Yr(r,e,s){if(fe(r,"hashLen"),fe(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const h=()=>{c.fill(1),l.fill(0),d=0},m=(...y)=>s(l,we(c,...y)),x=(y=n)=>{l=m(o,y),c=m(),y.length!==0&&(l=m(i,y),c=m())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const S=[];for(;y<e;){c=m();const C=c.slice();S.push(C),y+=c.length}return we(...S)};return(y,S)=>{h(),x(y);let C;for(;!(C=S(w()));)x();return h(),C}}function ct(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 zt(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 oe=BigInt(0),Q=BigInt(1),Ie=BigInt(2),jt=BigInt(3),Yt=BigInt(4),Xt=BigInt(5),Xr=BigInt(7),Zt=BigInt(8),Zr=BigInt(9),Qt=BigInt(16);function ue(r,e){const s=r%e;return s>=oe?s:e+s}function le(r,e,s){let t=r;for(;e-- >oe;)t*=t,t%=s;return t}function es(r,e){if(r===oe)throw new Error("invert: expected non-zero number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let s=ue(r,e),t=e,n=oe,o=Q;for(;s!==oe;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==Q)throw new Error("invert: does not exist");return ue(n,e)}function lt(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+Q)/Yt,t=r.pow(e,s);return lt(r,t,e),t}function Qr(r,e){const s=(r.ORDER-Xt)/Zt,t=r.mul(e,Ie),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,Ie),n),a=r.mul(o,r.sub(i,r.ONE));return lt(r,a,e),a}function en(r){const e=Xe(r),s=ss(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Xr)/Qt;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const h=a.mul(l,n),m=a.mul(l,o),x=a.eql(a.sqr(d),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,d,x),d=a.cmov(m,h,w);const I=a.eql(a.sqr(d),c),y=a.cmov(l,d,I);return lt(a,y,c),y}}function ss(r){if(r<jt)throw new Error("sqrt is not defined for small field");let e=r-Q,s=0;for(;e%Ie===oe;)e/=Ie,s++;let t=Ie;const n=Xe(r);for(;ns(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+Q)/Ie;return function(c,l){if(c.is0(l))return l;if(ns(c,l)!==1)throw new Error("Cannot find square root");let d=s,h=c.mul(c.ONE,o),m=c.pow(l,e),x=c.pow(l,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let w=1,I=c.sqr(m);for(;!c.eql(I,c.ONE);)if(w++,I=c.sqr(I),w===d)throw new Error("Cannot find square root");const y=Q<<BigInt(d-w-1),S=c.pow(h,y);d=w,h=c.sqr(S),m=c.mul(m,h),x=c.mul(x,S)}return x}}function tn(r){return r%Yt===jt?ts:r%Zt===Xt?Qr:r%Qt===Zr?en(r):ss(r)}const sn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rn(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=sn.reduce((t,n)=>(t[n]="function",t),e);return ct(r,s),r}function nn(r,e,s){if(s<oe)throw new Error("invalid exponent, negatives unsupported");if(s===oe)return r.ONE;if(s===Q)return e;let t=r.ONE,n=e;for(;s>oe;)s&Q&&(t=r.mul(t,n)),n=r.sqr(n),s>>=Q;return t}function rs(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 ns(r,e){const s=(r.ORDER-Q)/Ie,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 on(r,e){e!==void 0&&fe(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class an{constructor(e,s={}){E(this,"ORDER");E(this,"BITS");E(this,"BYTES");E(this,"isLE");E(this,"ZERO",oe);E(this,"ONE",Q);E(this,"_lengths");E(this,"_sqrt");E(this,"_mod");var i;if(e<=oe)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}=on(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 oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}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 nn(this,e,s)}div(e,s){return ue(e*es(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 es(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=tn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Jt(e,this.BYTES):it(e,this.BYTES)}fromBytes(e,s=!1){K(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?Kt(e):je(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 rs(this,e)}cmov(e,s,t){return t?s:e}}function Xe(r,e={}){return new an(r,e)}function os(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 is(r){const e=os(r);return e+Math.ceil(e/2)}function cn(r,e,s=!1){K(r);const t=r.length,n=os(e),o=is(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?Kt(r):je(r),a=ue(i,e-Q)+Q;return s?Jt(a,n):it(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ke=BigInt(0),Te=BigInt(1);function Ze(r,e){const s=e.negate();return r?s:e}function as(r,e){const s=rs(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function cs(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function dt(r,e){cs(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=at(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function ls(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,d=l+Math.abs(a)-1,h=a===0,m=a<0,x=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:m,isNegF:x,offsetF:l}}const ut=new WeakMap,ds=new WeakMap;function ht(r){return ds.get(r)||1}function us(r){if(r!==ke)throw new Error("invalid wNAF")}class ln{constructor(e,s){E(this,"BASE");E(this,"ZERO");E(this,"Fn");E(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>ke;)s&Te&&(t=t.add(n)),n=n.double(),s>>=Te;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=dt(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=dt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:m,offsetF:x}=ls(t,a,i);t=c,d?o=o.add(Ze(m,s[x])):n=n.add(Ze(h,s[l]))}return us(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=dt(e,this.bits);for(let i=0;i<o.windows&&t!==ke;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=ls(t,i,o);if(t=a,!l){const h=s[c];n=n.add(d?h.negate():h)}}return us(t),n}getPrecomputes(e,s,t){let n=ut.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),ut.set(s,n))),n}cached(e,s,t){const n=ht(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=ht(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){cs(s,this.bits),ds.set(e,s),ut.delete(e)}hasCache(e){return ht(e)!==1}}function dn(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>ke||t>ke;)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 hs(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return rn(e),e}else return Xe(r,{isLE:s})}function un(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>ke))throw new Error(`CURVE.${c} must be positive bigint`)}const n=hs(e.p,s.Fp,t),o=hs(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 hn(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class ps{constructor(e,s){E(this,"oHash");E(this,"iHash");E(this,"blockLen");E(this,"outputLen");E(this,"finished",!1);E(this,"destroyed",!1);if(Mt(e),K(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),Pe(n)}update(e){return Re(this),this.iHash.update(e),this}digestInto(e){Re(this),K(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 fs=(r,e,s)=>new ps(r,e).update(s).digest();fs.create=(r,e)=>new ps(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _s=(r,e)=>(r+(r>=0?e:-e)/gs)/e;function pn(r,e,s){const[[t,n],[o,i]]=e,a=_s(i*r,s),c=_s(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const h=l<ge,m=d<ge;h&&(l=-l),m&&(d=-d);const x=at(Math.ceil(jr(s)/2))+Ne;if(l<ge||l>=x||d<ge||d>=x)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:m,k2:d}}function pt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ft(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Je(s.lowS,"lowS"),Je(s.prehash,"prehash"),s.format!==void 0&&pt(s.format),s}class fn extends Error{constructor(e=""){super(e)}}const ve={Err:fn,_tlv:{encode:(r,e)=>{const{Err:s}=ve;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=ze(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?ze(n.length/2|128):"";return ze(r)+o+n+e},decode(r,e){const{Err:s}=ve;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 d of l)i=i<<8|d;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}=ve;if(r<ge)throw new e("integer: negative integers are not allowed");let s=ze(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}=ve;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 je(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ve,n=K(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:d}=t.decode(2,c);if(d.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}=ve,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),gs=BigInt(2),Qe=BigInt(3),_n=BigInt(4);function gn(r,e={}){const s=un("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;ct(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=ms(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(k,_,g){const{x:b,y:A}=_.toAffine(),L=t.toBytes(b);if(Je(g,"isCompressed"),g){d();const O=!t.isOdd(A);return we(xs(O),L)}else return we(Uint8Array.of(4),L,t.toBytes(A))}function m(k){K(k,void 0,"Point");const{publicKey:_,publicKeyUncompressed:g}=l,b=k.length,A=k[0],L=k.subarray(1);if(b===_&&(A===2||A===3)){const O=t.fromBytes(L);if(!t.isValid(O))throw new Error("bad point: is not on curve, wrong x");const M=I(O);let T;try{T=t.sqrt(M)}catch(Y){const V=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const $=t.isOdd(T);return(A&1)===1!==$&&(T=t.neg(T)),{x:O,y:T}}else if(b===g&&A===4){const O=t.BYTES,M=t.fromBytes(L.subarray(0,O)),T=t.fromBytes(L.subarray(O,O*2));if(!y(M,T))throw new Error("bad point: is not on curve");return{x:M,y:T}}else throw new Error(`bad point: got length ${b}, expected compressed=${_} or uncompressed=${g}`)}const x=e.toBytes||h,w=e.fromBytes||m;function I(k){const _=t.sqr(k),g=t.mul(_,k);return t.add(t.add(g,t.mul(k,o.a)),o.b)}function y(k,_){const g=t.sqr(_),b=I(k);return t.eql(g,b)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const S=t.mul(t.pow(o.a,Qe),_n),C=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(S,C)))throw new Error("bad curve params: a or b");function U(k,_,g=!1){if(!t.isValid(_)||g&&t.is0(_))throw new Error(`bad point coordinate ${k}`);return _}function v(k){if(!(k instanceof G))throw new Error("Weierstrass Point expected")}function P(k){if(!c||!c.basises)throw new Error("no endo");return pn(k,c.basises,n.ORDER)}const N=zt((k,_)=>{const{X:g,Y:b,Z:A}=k;if(t.eql(A,t.ONE))return{x:g,y:b};const L=k.is0();_==null&&(_=L?t.ONE:t.inv(A));const O=t.mul(g,_),M=t.mul(b,_),T=t.mul(A,_);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:O,y:M}}),W=zt(k=>{if(k.is0()){if(e.allowInfinityPoint&&!t.is0(k.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:g}=k.toAffine();if(!t.isValid(_)||!t.isValid(g))throw new Error("bad point: x or y not field elements");if(!y(_,g))throw new Error("bad point: equation left != right");if(!k.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function J(k,_,g,b,A){return g=new G(t.mul(g.X,k),g.Y,g.Z),_=Ze(b,_),g=Ze(A,g),_.add(g)}const R=class R{constructor(_,g,b){E(this,"X");E(this,"Y");E(this,"Z");this.X=U("x",_),this.Y=U("y",g,!0),this.Z=U("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){const{x:g,y:b}=_||{};if(!_||!t.isValid(g)||!t.isValid(b))throw new Error("invalid affine point");if(_ instanceof R)throw new Error("projective point not allowed");return t.is0(g)&&t.is0(b)?R.ZERO:new R(g,b,t.ONE)}static fromBytes(_){const g=R.fromAffine(w(K(_,void 0,"point")));return g.assertValidity(),g}static fromHex(_){return R.fromBytes(Ve(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,g=!0){return D.createCache(this,_),g||this.multiply(Qe),this}assertValidity(){W(this)}hasEvenY(){const{y:_}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(_)}equals(_){v(_);const{X:g,Y:b,Z:A}=this,{X:L,Y:O,Z:M}=_,T=t.eql(t.mul(g,M),t.mul(L,A)),$=t.eql(t.mul(b,M),t.mul(O,A));return T&&$}negate(){return new R(this.X,t.neg(this.Y),this.Z)}double(){const{a:_,b:g}=o,b=t.mul(g,Qe),{X:A,Y:L,Z:O}=this;let M=t.ZERO,T=t.ZERO,$=t.ZERO,F=t.mul(A,A),Y=t.mul(L,L),V=t.mul(O,O),H=t.mul(A,L);return H=t.add(H,H),$=t.mul(A,O),$=t.add($,$),M=t.mul(_,$),T=t.mul(b,V),T=t.add(M,T),M=t.sub(Y,T),T=t.add(Y,T),T=t.mul(M,T),M=t.mul(H,M),$=t.mul(b,$),V=t.mul(_,V),H=t.sub(F,V),H=t.mul(_,H),H=t.add(H,$),$=t.add(F,F),F=t.add($,F),F=t.add(F,V),F=t.mul(F,H),T=t.add(T,F),V=t.mul(L,O),V=t.add(V,V),F=t.mul(V,H),M=t.sub(M,F),$=t.mul(V,Y),$=t.add($,$),$=t.add($,$),new R(M,T,$)}add(_){v(_);const{X:g,Y:b,Z:A}=this,{X:L,Y:O,Z:M}=_;let T=t.ZERO,$=t.ZERO,F=t.ZERO;const Y=o.a,V=t.mul(o.b,Qe);let H=t.mul(g,L),X=t.mul(b,O),se=t.mul(A,M),ce=t.add(g,b),z=t.add(L,O);ce=t.mul(ce,z),z=t.add(H,X),ce=t.sub(ce,z),z=t.add(g,A);let re=t.add(L,M);return z=t.mul(z,re),re=t.add(H,se),z=t.sub(z,re),re=t.add(b,A),T=t.add(O,M),re=t.mul(re,T),T=t.add(X,se),re=t.sub(re,T),F=t.mul(Y,z),T=t.mul(V,se),F=t.add(T,F),T=t.sub(X,F),F=t.add(X,F),$=t.mul(T,F),X=t.add(H,H),X=t.add(X,H),se=t.mul(Y,se),z=t.mul(V,z),X=t.add(X,se),se=t.sub(H,se),se=t.mul(Y,se),z=t.add(z,se),H=t.mul(X,z),$=t.add($,H),H=t.mul(re,z),T=t.mul(ce,T),T=t.sub(T,H),H=t.mul(ce,X),F=t.mul(re,F),F=t.add(F,H),new R(T,$,F)}subtract(_){return this.add(_.negate())}is0(){return this.equals(R.ZERO)}multiply(_){const{endo:g}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let b,A;const L=O=>D.cached(this,O,M=>as(R,M));if(g){const{k1neg:O,k1:M,k2neg:T,k2:$}=P(_),{p:F,f:Y}=L(M),{p:V,f:H}=L($);A=Y.add(H),b=J(g.beta,F,V,O,T)}else{const{p:O,f:M}=L(_);b=O,A=M}return as(R,[b,A])[0]}multiplyUnsafe(_){const{endo:g}=e,b=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===ge||b.is0())return R.ZERO;if(_===Ne)return b;if(D.hasCache(this))return this.multiply(_);if(g){const{k1neg:A,k1:L,k2neg:O,k2:M}=P(_),{p1:T,p2:$}=dn(R,b,L,M);return J(g.beta,T,$,A,O)}else return D.unsafe(b,_)}toAffine(_){return N(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return i===Ne?!0:_?_(R,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return i===Ne?this:_?_(R,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(_=!0){return Je(_,"isCompressed"),this.assertValidity(),x(R,this,_)}toHex(_=!0){return De(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};E(R,"BASE",new R(o.Gx,o.Gy,t.ONE)),E(R,"ZERO",new R(t.ZERO,t.ONE,t.ZERO)),E(R,"Fp",t),E(R,"Fn",n);let G=R;const q=n.BITS,D=new ln(G,e.endo?Math.ceil(q/2):q);return G.BASE.precompute(8),G}function xs(r){return Uint8Array.of(r?2:3)}function ms(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function xn(r,e={}){const{Fn:s}=r,t=e.randomBytes||Wt,n=Object.assign(ms(r.Fp,s),{seed:is(s.ORDER)});function o(x){try{const w=s.fromBytes(x);return s.isValidNot0(w)}catch{return!1}}function i(x,w){const{publicKey:I,publicKeyUncompressed:y}=n;try{const S=x.length;return w===!0&&S!==I||w===!1&&S!==y?!1:!!r.fromBytes(x)}catch{return!1}}function a(x=t(n.seed)){return cn(K(x,n.seed,"seed"),s.ORDER)}function c(x,w=!0){return r.BASE.multiply(s.fromBytes(x)).toBytes(w)}function l(x){const{secretKey:w,publicKey:I,publicKeyUncompressed:y}=n;if(!st(x)||"_lengths"in s&&s._lengths||w===I)return;const S=K(x,void 0,"key").length;return S===I||S===y}function d(x,w,I=!0){if(l(x)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(x);return r.fromBytes(w).multiply(y).toBytes(I)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=hn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:h,lengths:n})}function mn(r,e,s={}){Mt(e),ct(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Wt,n=s.hmac||((_,g)=>fs(e,_,g)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:x}=xn(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},I=a*gs<o.ORDER;function y(_){const g=a>>Ne;return _>g}function S(_,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return g}function C(){if(I)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(_,g){pt(g);const b=x.signature,A=g==="compact"?b:g==="recovered"?b+1:void 0;return K(_,A)}class v{constructor(g,b,A){E(this,"r");E(this,"s");E(this,"recovery");if(this.r=S("r",g),this.s=S("s",b),A!=null){if(C(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(g,b=w.format){U(g,b);let A;if(b==="der"){const{r:T,s:$}=ve.toSig(K(g));return new v(T,$)}b==="recovered"&&(A=g[0],b="compact",g=g.subarray(1));const L=x.signature/2,O=g.subarray(0,L),M=g.subarray(L,L*2);return new v(i.fromBytes(O),i.fromBytes(M),A)}static fromHex(g,b){return this.fromBytes(Ve(g),b)}assertRecovery(){const{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new v(this.r,this.s,g)}recoverPublicKey(g){const{r:b,s:A}=this,L=this.assertRecovery(),O=L===2||L===3?b+a:b;if(!o.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(O),T=r.fromBytes(we(xs((L&1)===0),M)),$=i.inv(O),F=N(K(g,void 0,"msgHash")),Y=i.create(-F*$),V=i.create(A*$),H=r.BASE.multiplyUnsafe(Y).add(T.multiplyUnsafe(V));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(g=w.format){if(pt(g),g==="der")return Ve(ve.hexFromSig(this));const{r:b,s:A}=this,L=i.toBytes(b),O=i.toBytes(A);return g==="recovered"?(C(),we(Uint8Array.of(this.assertRecovery()),L,O)):we(L,O)}toHex(g){return De(this.toBytes(g))}}const P=s.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const b=je(g),A=g.length*8-c;return A>0?b>>BigInt(A):b},N=s.bits2int_modN||function(g){return i.create(P(g))},W=at(c);function J(_){return zr("num < 2^"+c,_,ge,W),i.toBytes(_)}function G(_,g){return K(_,void 0,"message"),g?K(e(_),void 0,"prehashed message"):_}function q(_,g,b){const{lowS:A,prehash:L,extraEntropy:O}=ft(b,w);_=G(_,L);const M=N(_),T=i.fromBytes(g);if(!i.isValidNot0(T))throw new Error("invalid private key");const $=[J(T),J(M)];if(O!=null&&O!==!1){const H=O===!0?t(x.secretKey):O;$.push(K(H,void 0,"extraEntropy"))}const F=we(...$),Y=M;function V(H){const X=P(H);if(!i.isValidNot0(X))return;const se=i.inv(X),ce=r.BASE.multiply(X).toAffine(),z=i.create(ce.x);if(z===ge)return;const re=i.create(se*i.create(Y+z*T));if(re===ge)return;let Ds=(ce.x===z?0:2)|Number(ce.y&Ne),Ms=re;return A&&y(re)&&(Ms=i.neg(re),Ds^=1),new v(z,Ms,I?void 0:Ds)}return{seed:F,k2sig:V}}function D(_,g,b={}){const{seed:A,k2sig:L}=q(_,g,b);return Yr(e.outputLen,i.BYTES,n)(A,L).toBytes(b.format)}function R(_,g,b,A={}){const{lowS:L,prehash:O,format:M}=ft(A,w);if(b=K(b,void 0,"publicKey"),g=G(g,O),!st(_)){const T=_ instanceof v?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}U(_,M);try{const T=v.fromBytes(_,M),$=r.fromBytes(b);if(L&&T.hasHighS())return!1;const{r:F,s:Y}=T,V=N(g),H=i.inv(Y),X=i.create(V*H),se=i.create(F*H),ce=r.BASE.multiplyUnsafe(X).add($.multiplyUnsafe(se));return ce.is0()?!1:i.create(ce.x)===F}catch{return!1}}function k(_,g,b={}){const{prehash:A}=ft(b,w);return g=G(g,A),v.fromBytes(_,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:x,Point:r,sign:D,verify:R,recoverPublicKey:k,Signature:v,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _t={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},wn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ws=BigInt(2);function yn(r){const e=_t.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,d=l*l*r%e,h=le(d,s,e)*d%e,m=le(h,s,e)*d%e,x=le(m,ws,e)*l%e,w=le(x,n,e)*x%e,I=le(w,o,e)*w%e,y=le(I,a,e)*I%e,S=le(y,c,e)*y%e,C=le(S,a,e)*I%e,U=le(C,s,e)*d%e,v=le(U,i,e)*w%e,P=le(v,t,e)*l%e,N=le(P,ws,e);if(!gt.eql(gt.sqr(N),r))throw new Error("Cannot find square root");return N}const gt=Xe(_t.p,{sqrt:yn}),bn=mn(gn(_t,{Fp:gt,endo:wn}),Vr),vn=BigInt(0),Me=BigInt(1),Sn=BigInt(2),En=BigInt(7),In=BigInt(256),Tn=BigInt(113),ys=[],bs=[],vs=[];for(let r=0,e=Me,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ys.push(2*(5*t+s)),bs.push((r+1)*(r+2)/2%64);let n=vn;for(let o=0;o<7;o++)e=(e<<Me^(e>>En)*Tn)%In,e&Sn&&(n^=Me<<(Me<<BigInt(o))-Me);vs.push(n)}const Ss=$r(vs,!0),An=Ss[0],Rn=Ss[1],Es=(r,e,s)=>s>32?Hr(r,e,s):Br(r,e,s),Is=(r,e,s)=>s>32?Fr(r,e,s):Ur(r,e,s);function Pn(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],d=s[c+1],h=Es(l,d,1)^s[a],m=Is(l,d,1)^s[a+1];for(let x=0;x<50;x+=10)r[i+x]^=h,r[i+x+1]^=m}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=bs[i],c=Es(n,o,a),l=Is(n,o,a),d=ys[i];n=r[d],o=r[d+1],r[d]=c,r[d+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]^=An[t],r[1]^=Rn[t]}Pe(s)}class xt{constructor(e,s,t,n=!1,o=24){E(this,"state");E(this,"pos",0);E(this,"posOut",0);E(this,"finished",!1);E(this,"state32");E(this,"destroyed",!1);E(this,"blockLen");E(this,"suffix");E(this,"outputLen");E(this,"enableXOF",!1);E(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,fe(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ar(this.state)}clone(){return this._cloneInto()}keccak(){Bt(this.state32),Pn(this.state32,this.rounds),Bt(this.state32),this.posOut=0,this.pos=0}update(e){Re(this),K(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){Re(this,!1),K(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 fe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($t(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,Pe(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new xt(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 Ts=((r,e,s,t={})=>Ft(()=>new xt(e,r,s),t))(1,136,32);class kn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Tr(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
2
+ ${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=Nn(a),l=c.slice(0,32),d=c.slice(32,64),h=c[64],m=h>=27?h-27:h,I=new bn.Signature(As(l),As(d)).addRecoveryBit(m).recoverPublicKey(i).toBytes(!1).slice(1),y=Ts(I);return"0x"+De(y.slice(12))}}function Nn(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 As(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const On=3e4;class Cn{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??On);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)}}}class Se{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=Se.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n==="")throw u.error("[CROSSx] nonce claim 누락 — JWT payload 전체 키 목록:",Object.keys(t)),u.error("[CROSSx] 원인 추정: OAuth 서버가 Google/Apple 인증 요청에 nonce 파라미터를 포함하지 않았을 수 있습니다.","서버 로그에서 /auth/google, /auth/apple 요청 URL에 nonce 쿼리가 있는지 확인하세요."),new Error("ID Token에 nonce claim이 없습니다 — OAuth 서버 설정을 확인해 주세요");if(o.includes("appleid.apple.com")){const i=await Se.sha256Hex(s);if(u.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(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.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=Se.generateRandom16Hex(),l=Se.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const m=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!m){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const x=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),v(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,I=30;let y=0,S=null;const C=()=>{clearInterval(U),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+I+"초간 대기합니다"),S=setTimeout(()=>{v(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},I*1e3)},U=setInterval(()=>{y++;try{m.closed&&(y<=w?C():(v(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),v=()=>{clearTimeout(x),clearInterval(U),S&&clearTimeout(S),window.removeEventListener("message",P)},P=N=>{var J,G,q,D,R;if(N.origin!==e.expectedOrigin)return;v(),u.log("[CROSSx] OAuth postMessage 수신 — status:",N.data.status);const W=N.data.state??((J=N.data.data)==null?void 0:J.state);if(!W||W!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(N.data.status==="success"){const k=(G=N.data.data)==null?void 0:G.idToken,_=(q=N.data.data)==null?void 0:q.accessToken,g=_??k;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!_,hasIdToken:!!k}),!g){u.error("[CROSSx] 토큰을 찾을 수 없음:",N.data),t(new Error("Token not found in response"));return}if(k){try{const b=Se.parseJwtPayload(k);u.log("[CROSSx] idToken JWT payload 요약:",{iss:b.iss,sub:typeof b.sub=="string"?`${b.sub.slice(0,6)}...`:"(absent)",hasNonceClaim:"nonce"in b,nonceClaimType:typeof b.nonce,appleNonceSupported:b.nonce_supported??"(field absent)"})}catch{u.warn("[CROSSx] idToken JWT payload 파싱 실패 — 토큰 형식을 확인하세요")}Se.verifyIdTokenNonce(k,l).then(()=>s(g)).catch(b=>{u.error("[CROSSx] nonce 검증 실패:",b),t(b instanceof Error?b:new Error("nonce verification failed"))})}else s(g)}else u.error("[CROSSx] OAuth 실패:",(D=N.data.data)==null?void 0:D.error),t(new Error(((R=N.data.data)==null?void 0:R.error)||"Authentication failed"))};window.addEventListener("message",P)})}}const $e="crossx_wallet_data",Oe="crossx_mock_pin_hash";class Ln{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get($e)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get($e);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($e,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Oe,o),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new f(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get($e);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 u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,o,i){return u.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 u.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){u.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 u.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(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Oe);return s&&s!==e?!1:(s||await this.storage.set(Oe,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new f(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Oe);if(n&&t&&n!==t)throw new f(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Oe,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new f(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new f(p.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($e,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Oe,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Be{constructor(e,s,t,n,o){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}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new f(p.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const h=d.message||d.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:h,url:o,method:e,fullResponse:d});const m=Be.mapGatewayError(d.code,d.data),x=Be.getGatewayErrorMessage(d.code,h),w=d.data,I=m===p.PIN_LOCKED?Be.extractLockDetails(w):w??void 0,y=new f(m,x,I);throw y.gatewayCode=d.code,y.gatewayMessage=h,m===p.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(u.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof f)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,h=d.message||d.data||"API 요청에 실패했습니다",m=d.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:m,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new f(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${m}): ${h}`)}throw l}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new f(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}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 f(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new f(p.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 f(p.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){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.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};return(await this.request("POST","/mnemonic/verify-password",s)).verified}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 f(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??e,t=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);return t?{lockExpiresAt:t>1e10?t:t*1e3}:{}}static mapGatewayError(e,s){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10028:return p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";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 is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Invalid PIN format. Please enter a 6-digit numeric PIN.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";default:return`Request failed (${e}): ${s}`}}}class Ue{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Ue.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?rr:sr;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 f(Ue.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ue.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new f(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(He).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const Rs="__crossx-confirm-style",ee="__crossx-confirm-overlay",Dn={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 Ps(r,e){const s=Dn[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 Mn=`
3
3
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
4
4
 
5
- #${K} {
5
+ #${ee} {
6
6
  position: fixed;
7
7
  inset: 0;
8
8
  z-index: 2147483647;
@@ -390,13 +390,13 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
390
390
  gap: 8px;
391
391
  }
392
392
  .__crossx-pw-notice-icon {
393
- width: 28px;
394
- height: 28px;
393
+ width: 24px;
394
+ height: 24px;
395
395
  flex-shrink: 0;
396
396
  color: var(--cx-error);
397
397
  }
398
398
  .__crossx-pw-notice-title {
399
- font-size: 22px;
399
+ font-size: 24px;
400
400
  font-weight: 600;
401
401
  line-height: 1.3;
402
402
  color: var(--cx-error);
@@ -1135,7 +1135,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1135
1135
 
1136
1136
  /* ── Mobile bottom sheet ───────────────────────────────────── */
1137
1137
  @media (max-width: 480px) {
1138
- #${K} { align-items: flex-end; }
1138
+ #${ee} { align-items: flex-end; }
1139
1139
  .__crossx-card {
1140
1140
  width: 100%;
1141
1141
  max-width: 100%;
@@ -1191,6 +1191,53 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1191
1191
  .__crossx-card--password .__crossx-pw-notice-title { font-size: 20px; }
1192
1192
  .__crossx-card--password .__crossx-pw-fg--confirm { margin-top: 0; }
1193
1193
  .__crossx-home-indicator { display: flex; }
1194
+ /* ── PIN6 모바일 bottom sheet ── */
1195
+ .__crossx-card--pin6 {
1196
+ width: 100% !important;
1197
+ max-width: 100% !important;
1198
+ border-radius: 20px 20px 0 0 !important;
1199
+ border: 1px solid rgba(18,18,18,0.05) !important;
1200
+ border-bottom: none !important;
1201
+ max-height: 92vh;
1202
+ overflow: hidden;
1203
+ display: flex;
1204
+ flex-direction: column;
1205
+ }
1206
+ .__crossx-card--pin6 > .__crossx-divider { display: none; }
1207
+ .__crossx-card--pin6 .__crossx-header {
1208
+ padding: 16px 20px;
1209
+ flex-shrink: 0;
1210
+ }
1211
+ .__crossx-card--pin6 .__crossx-title { font-size: 16px; margin-bottom: 0; }
1212
+ .__crossx-card--pin6 .__crossx-pw-subtitle { display: none; }
1213
+ /* Notice 화면 body (pw-body) */
1214
+ .__crossx-card--pin6 .__crossx-pw-body {
1215
+ flex: 1;
1216
+ min-height: 0;
1217
+ overflow-y: auto;
1218
+ -webkit-overflow-scrolling: touch;
1219
+ padding: 16px 20px 20px;
1220
+ gap: 16px;
1221
+ }
1222
+ .__crossx-card--pin6 .__crossx-pw-fields--notice {
1223
+ flex: 1;
1224
+ min-height: 0;
1225
+ overflow-y: auto;
1226
+ -webkit-overflow-scrolling: touch;
1227
+ }
1228
+ .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 20px; }
1229
+ .__crossx-card--pin6 .__crossx-pw-notice-icon { width: 20px; height: 20px; }
1230
+ .__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
1231
+ /* PIN 입력 body */
1232
+ .__crossx-card--pin6 .__crossx-pin6-body {
1233
+ flex: 1;
1234
+ min-height: 0;
1235
+ overflow-y: auto;
1236
+ -webkit-overflow-scrolling: touch;
1237
+ padding: 16px 20px 20px;
1238
+ gap: 16px;
1239
+ }
1240
+ .__crossx-home-indicator { display: flex; }
1194
1241
  }
1195
1242
  @keyframes __crossx-slide-up-mobile {
1196
1243
  from { transform: translateY(100%); }
@@ -1218,7 +1265,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1218
1265
 
1219
1266
  /* ── Landscape for signing/transaction modals ──────────── */
1220
1267
  @media (orientation: landscape) and (max-height: 500px) {
1221
- #${K} { align-items: center !important; overflow: hidden; }
1268
+ #${ee} { align-items: center !important; overflow: hidden; }
1222
1269
  .__crossx-card--send-tx,
1223
1270
  .__crossx-card--sign-tx,
1224
1271
  .__crossx-card--sign-msg,
@@ -1356,57 +1403,228 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1356
1403
  /* Consent / notice modal adjustments */
1357
1404
  .__crossx-card--password .__crossx-pw-notice-title { font-size: 18px; }
1358
1405
  .__crossx-card--password .__crossx-pw-notice-item { padding: 12px 14px; }
1406
+
1407
+ /* ── PIN6 랜드스케이프 ─────────────────────────── */
1408
+ .__crossx-card--pin6 {
1409
+ width: 480px;
1410
+ max-width: calc(100vw - 32px);
1411
+ border-radius: 24px;
1412
+ border-bottom: 4px solid var(--cx-border);
1413
+ max-height: calc(100vh - 32px);
1414
+ overflow: hidden;
1415
+ display: flex;
1416
+ flex-direction: column;
1417
+ animation: __crossx-slide-up 0.18s ease;
1418
+ }
1419
+ .__crossx-card--pin6 > .__crossx-divider { flex-shrink: 0; }
1420
+ .__crossx-card--pin6 .__crossx-header { flex-shrink: 0; padding: 16px 24px 12px; }
1421
+ .__crossx-card--pin6 .__crossx-pw-body {
1422
+ flex: 1;
1423
+ min-height: 0;
1424
+ overflow-y: auto;
1425
+ -webkit-overflow-scrolling: touch;
1426
+ padding: 16px 24px 20px;
1427
+ gap: 16px;
1428
+ }
1429
+ .__crossx-card--pin6 .__crossx-pw-fields {
1430
+ gap: 16px;
1431
+ }
1432
+ .__crossx-card--pin6 .__crossx-pw-fields--notice {
1433
+ flex: 1;
1434
+ min-height: 0;
1435
+ overflow-y: auto;
1436
+ -webkit-overflow-scrolling: touch;
1437
+ }
1438
+ .__crossx-card--pin6 .__crossx-pw-notice-title { font-size: 20px; }
1439
+ .__crossx-card--pin6 .__crossx-pw-btn { flex-shrink: 0; }
1440
+ .__crossx-card--pin6 .__crossx-pin6-body {
1441
+ flex: 1;
1442
+ min-height: 0;
1443
+ overflow-y: auto;
1444
+ padding: 16px 24px 20px;
1445
+ gap: 12px;
1446
+ }
1447
+ .__crossx-card--pin6 .__crossx-pin6-next { flex-shrink: 0; }
1448
+ }
1449
+
1450
+ /* ── 6-digit wallet PIN box input ──────────────────────────────────── */
1451
+ .__crossx-card--pin6 {
1452
+ width: 100%;
1453
+ max-width: 480px;
1454
+ }
1455
+ /* PIN6 Notice 화면 body/fields: Figma 기준 px-24, gap-16 */
1456
+ .__crossx-card--pin6 .__crossx-pw-body {
1457
+ padding: 20px 24px 24px;
1458
+ gap: 16px;
1459
+ }
1460
+ .__crossx-card--pin6 .__crossx-pw-fields {
1461
+ gap: 16px;
1462
+ }
1463
+ .__crossx-pin6-header-sub {
1464
+ font-size: 14px;
1465
+ font-weight: 400;
1466
+ color: rgba(18,18,18,0.7);
1467
+ line-height: 1.3;
1468
+ margin: 2px 0 0;
1469
+ }
1470
+ .__crossx-pin6-body {
1471
+ display: flex;
1472
+ flex-direction: column;
1473
+ align-items: center;
1474
+ padding: 20px 24px 24px;
1475
+ gap: 16px;
1476
+ width: 100%;
1477
+ }
1478
+ .__crossx-pin6-subtitle {
1479
+ font-size: 16px;
1480
+ font-weight: 500;
1481
+ color: rgba(18,18,18,0.5);
1482
+ text-align: center;
1483
+ margin: 0;
1484
+ line-height: 1.5;
1485
+ letter-spacing: -0.01em;
1486
+ width: 100%;
1487
+ }
1488
+ .__crossx-pin6-boxes {
1489
+ display: flex;
1490
+ gap: 8px;
1491
+ align-items: center;
1492
+ justify-content: center;
1493
+ padding: 8px 0;
1494
+ }
1495
+ .__crossx-pin6-box {
1496
+ width: 48px;
1497
+ height: 48px;
1498
+ border-radius: 12px;
1499
+ border: none;
1500
+ background: rgba(18,18,18,0.05);
1501
+ font-size: 24px;
1502
+ font-weight: 600;
1503
+ text-align: center;
1504
+ color: var(--cx-fg, #121212);
1505
+ outline: none;
1506
+ caret-color: transparent;
1507
+ letter-spacing: 0;
1508
+ -webkit-tap-highlight-color: transparent;
1509
+ transition: background 0.12s, box-shadow 0.12s;
1510
+ }
1511
+ .__crossx-pin6-box:focus {
1512
+ background: rgba(18,18,18,0.08);
1513
+ box-shadow: 0 0 0 2px var(--crossx-primary, #019d92);
1514
+ }
1515
+ .__crossx-pin6-box.--error {
1516
+ /* 에러 시 박스 자체에는 별도 스타일 없음 — 에러 텍스트로만 표시 */
1359
1517
  }
1360
- `;function le(){let r=document.getElementById(Cs);r||(r=document.createElement("style"),r.id=Cs,document.head.appendChild(r)),r.textContent=Do}function Y(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function Mo(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const o=yt(t,s);return o==="0"?null:`${o} ${e}`}catch{return null}}const ks={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Ps(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&ks[e]?ks[e]:r}function yt(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 bt(r){try{const e=BigInt(r),s=e/1000000000n,o=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return o?`${s}.${o}`:`${s}`}catch{return r}}function $o(r){try{return BigInt(r).toLocaleString()}catch{return r}}function Bo(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:o,nativeSymbol:n="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=$o(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${yt(l,i)} ${n}`,maxFeeGwei:bt(t),maxPriorityFeeGwei:o?bt(o):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${yt(l,i)} ${n}`,gasPriceGwei:bt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ns(r){const e=Bo(r);if(!e)return W("Estimated fee","<span>—</span>");let s=W("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=W("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=W("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=W("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=W("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const fe=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1518
+ .__crossx-pin6-box.--locked,
1519
+ .__crossx-pin6-box:disabled {
1520
+ opacity: 0.4;
1521
+ pointer-events: none;
1522
+ }
1523
+ .__crossx-pin6-boxes.--shake {
1524
+ animation: __crossx-pin6-shake 0.4s ease;
1525
+ }
1526
+ @keyframes __crossx-pin6-shake {
1527
+ 0%, 100% { transform: translateX(0); }
1528
+ 20% { transform: translateX(-8px); }
1529
+ 40% { transform: translateX(8px); }
1530
+ 60% { transform: translateX(-6px); }
1531
+ 80% { transform: translateX(6px); }
1532
+ }
1533
+ .__crossx-pin6-error {
1534
+ font-size: 14px;
1535
+ font-weight: 400;
1536
+ color: var(--cx-error, #e70077);
1537
+ text-align: center;
1538
+ margin: 0;
1539
+ min-height: 20px;
1540
+ line-height: 1.4;
1541
+ width: 100%;
1542
+ }
1543
+ /* 잠금 메시지 + 카운트다운 */
1544
+ .__crossx-pin6-lock-msg {
1545
+ display: flex;
1546
+ align-items: center;
1547
+ gap: 6px;
1548
+ font-size: 13px;
1549
+ font-weight: 500;
1550
+ color: var(--crossx-error);
1551
+ text-align: center;
1552
+ margin: 0;
1553
+ }
1554
+ .__crossx-pin6-lock-msg svg {
1555
+ flex-shrink: 0;
1556
+ color: var(--crossx-error);
1557
+ }
1558
+ /* Next 버튼 */
1559
+ .__crossx-pin6-next {
1560
+ width: 100%;
1561
+ padding: 16px;
1562
+ background: var(--crossx-primary, #019d92);
1563
+ color: white;
1564
+ border: none;
1565
+ border-radius: 12px;
1566
+ font-size: 18px;
1567
+ font-weight: 700;
1568
+ cursor: pointer;
1569
+ line-height: 1.3;
1570
+ transition: opacity 0.15s;
1571
+ -webkit-tap-highlight-color: transparent;
1572
+ }
1573
+ .__crossx-pin6-next:disabled,
1574
+ .__crossx-pin6-next.--disabled {
1575
+ opacity: 0.5;
1576
+ cursor: default;
1577
+ }
1578
+ `;function pe(){let r=document.getElementById(Rs);r||(r=document.createElement("style"),r.id=Rs,document.head.appendChild(r)),r.textContent=Mn}function te(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function $n(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=mt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const ks={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Ns(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&ks[e]?ks[e]:r}function mt(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 wt(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 Bn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function Un(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=Bn(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${mt(l,i)} ${o}`,maxFeeGwei:wt(t),maxPriorityFeeGwei:n?wt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${mt(l,i)} ${o}`,gasPriceGwei:wt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Os(r){const e=Un(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 xe=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1361
1579
  <rect x="9" y="9" width="13" height="13" rx="2"/>
1362
1580
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
1363
- </svg>`,te=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
1581
+ </svg>`,ae=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
1364
1582
  <line x1="18" y1="6" x2="6" y2="18"/>
1365
1583
  <line x1="6" y1="6" x2="18" y2="18"/>
1366
- </svg>`;function Uo(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
1584
+ </svg>`;function Hn(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
1367
1585
  <circle cx="14" cy="14" r="14" fill="${r}"/>
1368
1586
  <path d="M14 7.5L19.2 10.5V16.5L14 19.5L8.8 16.5V10.5L14 7.5Z" fill="white" opacity="0.9"/>
1369
- </svg>`}const vt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
1587
+ </svg>`}const yt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
1370
1588
  <rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
1371
1589
  <path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
1372
1590
  <rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
1373
- </svg>`,Fo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
1591
+ </svg>`,Fn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
1374
1592
  <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)"/>
1375
- </svg>`,Ho=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
1593
+ </svg>`,Wn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
1376
1594
  <circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
1377
1595
  <circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
1378
1596
  <path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
1379
- </svg>`;function oe(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 W(r,e){return`
1597
+ </svg>`;function de(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`
1380
1598
  <div class="__crossx-row">
1381
1599
  <span class="__crossx-row-label">${r}</span>
1382
1600
  <div class="__crossx-row-value">${e}</div>
1383
- </div>`}function Go(r,e){const s=e,t=Xe(),o=r.to?`<span class="__crossx-addr-text">${Y(r.to)}</span>
1384
- <button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${fe}</button>`:"<span>—</span>",n=Ns(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=K,a.innerHTML=`
1385
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${oe(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1601
+ </div>`}function Gn(r,e){const s=e,t=et(),n=r.to?`<span class="__crossx-addr-text">${te(r.to)}</span>
1602
+ <button class="__crossx-copy-btn" data-copy="${B(r.to)}" title="Copy address">${xe}</button>`:"<span>—</span>",o=Os(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=ee,a.innerHTML=`
1603
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${de(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1386
1604
  <div class="__crossx-header">
1387
1605
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
1388
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1606
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1389
1607
  </div>
1390
1608
  <hr class="__crossx-divider">
1391
1609
  <div class="__crossx-body">
1392
1610
  <div class="__crossx-body-cols">
1393
1611
  <div class="__crossx-col-left">
1394
1612
  <p class="__crossx-sig-subtitle">
1395
- <span class="__crossx-sig-origin">${T(t)} </span>is requesting a Signature
1613
+ <span class="__crossx-sig-origin">${B(t)} </span>is requesting a Signature
1396
1614
  </p>
1397
1615
  <div class="__crossx-addr-pill">
1398
- ${vt}
1399
- <span class="__crossx-addr-pill-text">${Y(r.from)}</span>
1616
+ ${yt}
1617
+ <span class="__crossx-addr-pill-text">${te(r.from)}</span>
1400
1618
  </div>
1401
1619
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
1402
1620
  <hr class="__crossx-divider">
1403
1621
  <div class="__crossx-rows">
1404
- ${W("To",o)}
1405
- ${W("Network",`<span>${Ps(r.chainId)}</span>`)}
1406
- ${n}
1622
+ ${j("To",n)}
1623
+ ${j("Network",`<span>${Ns(r.chainId)}</span>`)}
1624
+ ${o}
1407
1625
  </div>
1408
1626
  </div>
1409
- <pre class="__crossx-raw-tx">${T(i)}</pre>
1627
+ <pre class="__crossx-raw-tx">${B(i)}</pre>
1410
1628
  </div>
1411
1629
  <div class="__crossx-btn-row">
1412
1630
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
@@ -1414,59 +1632,59 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1414
1632
  </div>
1415
1633
  </div>
1416
1634
  </div>
1417
- `,a}function Wo(r,e){const s=e,t=r.nativeSymbol??"ETH",o=r.nativeDecimals??18,n=Xe(),i=r.to?`<span class="__crossx-addr-text">${Y(r.to)}</span>
1418
- <button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${fe}</button>`:"<span>—</span>",a=Ns(r),l=Mo(r.value,t,o)??"—",d=document.createElement("div");return d.id=K,d.innerHTML=`
1419
- <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${oe(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1635
+ `,a}function qn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=et(),i=r.to?`<span class="__crossx-addr-text">${te(r.to)}</span>
1636
+ <button class="__crossx-copy-btn" data-copy="${B(r.to)}" title="Copy address">${xe}</button>`:"<span>—</span>",a=Os(r),l=$n(r.value,t,n)??"—",d=document.createElement("div");return d.id=ee,d.innerHTML=`
1637
+ <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${de(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1420
1638
  <div class="__crossx-header">
1421
1639
  <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
1422
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1640
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1423
1641
  </div>
1424
1642
  <hr class="__crossx-divider">
1425
1643
  <div class="__crossx-body">
1426
1644
  <p class="__crossx-tx-subtitle">
1427
- <span class="__crossx-sig-origin">${T(n)}</span> wants your permission to approve the following transaction.
1645
+ <span class="__crossx-sig-origin">${B(o)}</span> wants your permission to approve the following transaction.
1428
1646
  </p>
1429
1647
  <div class="__crossx-body-cols">
1430
1648
  <div class="__crossx-rows">
1431
- ${W("To",i)}
1432
- ${W("Network",`<span>${Ps(r.chainId)}</span>`)}
1649
+ ${j("To",i)}
1650
+ ${j("Network",`<span>${Ns(r.chainId)}</span>`)}
1433
1651
  ${a}
1434
1652
  </div>
1435
1653
  <div class="__crossx-pill">
1436
- <span class="__crossx-pill-from">${Y(r.from)}</span>
1654
+ <span class="__crossx-pill-from">${te(r.from)}</span>
1437
1655
  <span class="__crossx-pill-amount">${l}</span>
1438
1656
  </div>
1439
1657
  </div>
1440
1658
  <button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
1441
1659
  </div>
1442
1660
  </div>
1443
- `,d}function Xe(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function T(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function qo(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Vo(r){if(typeof r=="string")return T(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return T(JSON.stringify(r))}catch{return String(r)}}function Ko(r,e){const s=W("From",`<span class="__crossx-addr-text">${Y(r.from)}</span>
1444
- <button class="__crossx-copy-btn" data-copy="${T(r.from)}" title="Copy address">${fe}</button>`),t=r.to?W("To",`<span class="__crossx-addr-text">${Y(r.to)}</span>
1445
- <button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${fe}</button>`):"",o=r.amount?W("Transfer",`<span>${T(r.amount)}</span>`):"",n=r.fees?W("Tx Fee",`<span>${T(r.fees)}</span>`):"",i=r.txHash?W("Tx Hash",`<span class="__crossx-addr-text">${Y(r.txHash)}</span>
1446
- <button class="__crossx-copy-btn" data-copy="${T(r.txHash)}" title="Copy hash">${fe}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
1661
+ `,d}function et(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function B(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Vn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Kn(r){if(typeof r=="string")return B(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return B(JSON.stringify(r))}catch{return String(r)}}function Jn(r,e){const s=j("From",`<span class="__crossx-addr-text">${te(r.from)}</span>
1662
+ <button class="__crossx-copy-btn" data-copy="${B(r.from)}" title="Copy address">${xe}</button>`),t=r.to?j("To",`<span class="__crossx-addr-text">${te(r.to)}</span>
1663
+ <button class="__crossx-copy-btn" data-copy="${B(r.to)}" title="Copy address">${xe}</button>`):"",n=r.amount?j("Transfer",`<span>${B(r.amount)}</span>`):"",o=r.fees?j("Tx Fee",`<span>${B(r.fees)}</span>`):"",i=r.txHash?j("Tx Hash",`<span class="__crossx-addr-text">${te(r.txHash)}</span>
1664
+ <button class="__crossx-copy-btn" data-copy="${B(r.txHash)}" title="Copy hash">${xe}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
1447
1665
  <span class="__crossx-total-label">Total<br>(including fees)</span>
1448
- <span class="__crossx-total-amount">${T(r.total)}</span>
1449
- </div>`:"",c=document.createElement("div");return c.id=K,c.innerHTML=`
1450
- <div class="__crossx-card __crossx-card--migration" style="${oe(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1666
+ <span class="__crossx-total-amount">${B(r.total)}</span>
1667
+ </div>`:"",c=document.createElement("div");return c.id=ee,c.innerHTML=`
1668
+ <div class="__crossx-card __crossx-card--migration" style="${de(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1451
1669
  <div class="__crossx-header">
1452
1670
  <p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
1453
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1671
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1454
1672
  </div>
1455
1673
  <hr class="__crossx-divider">
1456
1674
  <div class="__crossx-body">
1457
1675
  <div class="__crossx-rows">
1458
1676
  ${s}
1459
1677
  ${t}
1460
- ${o}
1461
1678
  ${n}
1679
+ ${o}
1462
1680
  ${i}
1463
1681
  </div>
1464
1682
  ${a}
1465
1683
  <button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
1466
1684
  </div>
1467
1685
  </div>
1468
- `,c}function jo(r,e){const s=document.createElement("div");return s.id=K,s.innerHTML=`
1469
- <div class="__crossx-card __crossx-card--migration" style="${oe(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1686
+ `,c}function zn(r,e){const s=document.createElement("div");return s.id=ee,s.innerHTML=`
1687
+ <div class="__crossx-card __crossx-card--migration" style="${de(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1470
1688
  <div class="__crossx-header">
1471
1689
  <p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
1472
1690
  </div>
@@ -1478,43 +1696,43 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1478
1696
  </div>
1479
1697
  </div>
1480
1698
  </div>
1481
- `,s}function zo(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",o=e.status==="timeout",n=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(n){const f=o?Ho:t?"":Fo,b=o?"Transaction timeout":t?"Transaction complete":"Transaction failed";f?(n.style.display="flex",n.style.alignItems="center",n.style.gap="8px",n.innerHTML=`${f}<span>${b}</span>`):n.textContent=b}if(i&&!r.querySelector("#__crossx-close-btn")){const f=document.createElement("button");f.className="__crossx-close",f.id="__crossx-close-btn",f.setAttribute("aria-label","Close"),f.innerHTML=te,i.appendChild(f)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?W("From",`<span class="__crossx-addr-text">${Y(e.from)}</span>
1482
- <button class="__crossx-copy-btn" data-copy="${T(e.from)}" title="Copy address">${fe}</button>`):"",l=e.to?W("To",`<span class="__crossx-addr-text">${Y(e.to)}</span>
1483
- <button class="__crossx-copy-btn" data-copy="${T(e.to)}" title="Copy address">${fe}</button>`):"",d=e.amount?W("Transfer",`<span>${T(e.amount)}</span>`):"",u=e.fees?W("Tx Fee",`<span>${T(e.fees)}</span>`):"",g=e.txHash?W("Tx Hash",`<span class="__crossx-addr-text">${Y(e.txHash)}</span>
1484
- <button class="__crossx-copy-btn" data-copy="${T(e.txHash)}" title="Copy hash">${fe}</button>`):"",_=e.total?`<div class="__crossx-total-pill">
1699
+ `,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 w=n?Wn:t?"":Fn,I=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${I}</span>`):o.textContent=I}if(i&&!r.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ae,i.appendChild(w)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?j("From",`<span class="__crossx-addr-text">${te(e.from)}</span>
1700
+ <button class="__crossx-copy-btn" data-copy="${B(e.from)}" title="Copy address">${xe}</button>`):"",l=e.to?j("To",`<span class="__crossx-addr-text">${te(e.to)}</span>
1701
+ <button class="__crossx-copy-btn" data-copy="${B(e.to)}" title="Copy address">${xe}</button>`):"",d=e.amount?j("Transfer",`<span>${B(e.amount)}</span>`):"",h=e.fees?j("Tx Fee",`<span>${B(e.fees)}</span>`):"",m=e.txHash?j("Tx Hash",`<span class="__crossx-addr-text">${te(e.txHash)}</span>
1702
+ <button class="__crossx-copy-btn" data-copy="${B(e.txHash)}" title="Copy hash">${xe}</button>`):"",x=e.total?`<div class="__crossx-total-pill">
1485
1703
  <span class="__crossx-total-label">Total<br>(including fees)</span>
1486
- <span class="__crossx-total-amount">${T(e.total)}</span>
1704
+ <span class="__crossx-total-amount">${B(e.total)}</span>
1487
1705
  </div>`:"";a.innerHTML=`
1488
1706
  <div class="__crossx-rows">
1489
1707
  ${c}
1490
1708
  ${l}
1491
1709
  ${d}
1492
- ${u}
1493
- ${g}
1710
+ ${h}
1711
+ ${m}
1494
1712
  </div>
1495
- ${_}
1713
+ ${x}
1496
1714
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
1497
- `,a.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",b=>{var E;b.stopPropagation();const y=f.dataset.copy;y&&((E=navigator.clipboard)==null||E.writeText(y).catch(()=>{}))})})}function Jo(r,e){const s=e,t=Xe(),o=T(r.message),n=document.createElement("div");return n.id=K,n.innerHTML=`
1498
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${oe(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1715
+ `,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",I=>{var S;I.stopPropagation();const y=w.dataset.copy;y&&((S=navigator.clipboard)==null||S.writeText(y).catch(()=>{}))})})}function Yn(r,e){const s=e,t=et(),n=B(r.message),o=document.createElement("div");return o.id=ee,o.innerHTML=`
1716
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${de(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1499
1717
  <div class="__crossx-header">
1500
1718
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
1501
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1719
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1502
1720
  </div>
1503
1721
  <hr class="__crossx-divider">
1504
1722
  <div class="__crossx-body">
1505
1723
  <div class="__crossx-body-cols">
1506
1724
  <div class="__crossx-col-left">
1507
1725
  <p class="__crossx-sig-subtitle">
1508
- <span class="__crossx-sig-origin">${T(t)} </span>is requesting a Signature
1726
+ <span class="__crossx-sig-origin">${B(t)} </span>is requesting a Signature
1509
1727
  </p>
1510
1728
  <div class="__crossx-addr-pill">
1511
- ${vt}
1512
- <span class="__crossx-addr-pill-text">${Y(r.from)}</span>
1729
+ ${yt}
1730
+ <span class="__crossx-addr-pill-text">${te(r.from)}</span>
1513
1731
  </div>
1514
1732
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
1515
1733
  </div>
1516
1734
  <hr class="__crossx-divider __crossx-divider--cols">
1517
- <div class="__crossx-msg-raw">${o}</div>
1735
+ <div class="__crossx-msg-raw">${n}</div>
1518
1736
  </div>
1519
1737
  <div class="__crossx-btn-row">
1520
1738
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
@@ -1522,31 +1740,31 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1522
1740
  </div>
1523
1741
  </div>
1524
1742
  </div>
1525
- `,n}function Yo(r,e){const s=e,t=Xe();let o={};if(typeof r.typedData=="string")try{o=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(o=r.typedData);const n=o.primaryType??"—",i=o.message??{};let a=`
1743
+ `,o}function Xn(r,e){const s=e,t=et();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=`
1526
1744
  <div class="__crossx-td-row">
1527
1745
  <span class="__crossx-td-label">Primary Type</span>
1528
- <span class="__crossx-td-value">${T(n)}</span>
1529
- </div>`;for(const[l,d]of Object.entries(i)){const u=Vo(d),_=qo(d)?`<span class="__crossx-addr-text">${Y(d)}</span>
1530
- <button class="__crossx-copy-btn" data-copy="${T(String(d))}" title="Copy">${fe}</button>`:`<span>${u}</span>`;a+=`
1746
+ <span class="__crossx-td-value">${B(o)}</span>
1747
+ </div>`;for(const[l,d]of Object.entries(i)){const h=Kn(d),x=Vn(d)?`<span class="__crossx-addr-text">${te(d)}</span>
1748
+ <button class="__crossx-copy-btn" data-copy="${B(String(d))}" title="Copy">${xe}</button>`:`<span>${h}</span>`;a+=`
1531
1749
  <div class="__crossx-td-row">
1532
- <span class="__crossx-td-label">${T(l)}</span>
1533
- <div class="__crossx-td-value">${_}</div>
1534
- </div>`}const c=document.createElement("div");return c.id=K,c.innerHTML=`
1535
- <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${oe(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1750
+ <span class="__crossx-td-label">${B(l)}</span>
1751
+ <div class="__crossx-td-value">${x}</div>
1752
+ </div>`}const c=document.createElement("div");return c.id=ee,c.innerHTML=`
1753
+ <div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${de(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1536
1754
  <div class="__crossx-header">
1537
1755
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
1538
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1756
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1539
1757
  </div>
1540
1758
  <hr class="__crossx-divider">
1541
1759
  <div class="__crossx-body">
1542
1760
  <div class="__crossx-body-cols">
1543
1761
  <div class="__crossx-col-left">
1544
1762
  <p class="__crossx-sig-subtitle">
1545
- <span class="__crossx-sig-origin">${T(t)} </span>is requesting a Signature
1763
+ <span class="__crossx-sig-origin">${B(t)} </span>is requesting a Signature
1546
1764
  </p>
1547
1765
  <div class="__crossx-addr-pill">
1548
- ${vt}
1549
- <span class="__crossx-addr-pill-text">${Y(r.from)}</span>
1766
+ ${yt}
1767
+ <span class="__crossx-addr-pill-text">${te(r.from)}</span>
1550
1768
  </div>
1551
1769
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
1552
1770
  </div>
@@ -1559,19 +1777,19 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1559
1777
  </div>
1560
1778
  </div>
1561
1779
  </div>
1562
- `,c}const Zo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
1780
+ `,c}const Zn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
1563
1781
  <line x1="12" y1="5" x2="12" y2="19"/>
1564
1782
  <line x1="5" y1="12" x2="19" y2="12"/>
1565
- </svg>`;function Xo(r,e,s){const t=s==null?void 0:s.toLowerCase(),o=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${T(i.address)}">
1566
- <span class="__crossx-wallet-addr">${Y(i.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
1567
- </button>`}).join(""),n=document.createElement("div");return n.id=K,n.innerHTML=`
1568
- <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${oe(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1783
+ </svg>`;function Qn(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="${B(i.address)}">
1784
+ <span class="__crossx-wallet-addr">${te(i.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
1785
+ </button>`}).join(""),o=document.createElement("div");return o.id=ee,o.innerHTML=`
1786
+ <div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${de(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1569
1787
  <div class="__crossx-header">
1570
1788
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
1571
1789
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Select Connected Wallet</p>
1572
1790
  <p class="__crossx-subtitle--body">Please select the wallet you previously used for this game to continue.</p>
1573
1791
  </div>
1574
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1792
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1575
1793
  </div>
1576
1794
  <hr class="__crossx-divider">
1577
1795
  <div class="__crossx-body">
@@ -1585,42 +1803,42 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1585
1803
  <hr class="__crossx-divider __crossx-divider--cols">
1586
1804
  <div class="__crossx-col-right-ws">
1587
1805
  <div class="__crossx-wallet-list" id="__crossx-wallet-list">
1588
- ${o}
1806
+ ${n}
1589
1807
  </div>
1590
1808
  <button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
1591
- <span class="__crossx-wallet-add-icon">${Zo}</span>
1809
+ <span class="__crossx-wallet-add-icon">${Zn}</span>
1592
1810
  <span class="__crossx-wallet-add-label">add a wallet</span>
1593
1811
  </button>
1594
1812
  </div>
1595
1813
  </div>
1596
1814
  </div>
1597
1815
  </div>
1598
- `,n}const Qo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1816
+ `,o}const eo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1599
1817
  <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"/>
1600
1818
  <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"/>
1601
- </svg>`,en=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1819
+ </svg>`,to=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1602
1820
  <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"/>
1603
1821
  <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"/>
1604
1822
  <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"/>
1605
1823
  <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"/>
1606
- </svg>`;function tn(r){const e=r,s=document.createElement("div");return s.id=K,s.innerHTML=`
1607
- <div class="__crossx-card __crossx-card--migration" style="${oe(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1824
+ </svg>`;function so(r){const e=r,s=document.createElement("div");return s.id=ee,s.innerHTML=`
1825
+ <div class="__crossx-card __crossx-card--migration" style="${de(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1608
1826
  <div class="__crossx-header">
1609
1827
  <div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
1610
1828
  <p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Welcome onboard</p>
1611
1829
  <p class="__crossx-subtitle">Creating CROSSx Embedded Wallet</p>
1612
1830
  </div>
1613
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1831
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1614
1832
  </div>
1615
1833
  <hr class="__crossx-divider">
1616
1834
  <div class="__crossx-body">
1617
1835
  <div class="__crossx-login-btn-row">
1618
1836
  <button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
1619
- <span class="__crossx-login-icon" style="color:var(--cx-value);">${Qo}</span>
1837
+ <span class="__crossx-login-icon" style="color:var(--cx-value);">${eo}</span>
1620
1838
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Apple</span>
1621
1839
  </button>
1622
1840
  <button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
1623
- <span class="__crossx-login-icon">${en}</span>
1841
+ <span class="__crossx-login-icon">${to}</span>
1624
1842
  <span class="__crossx-login-btn-label">Sign in with&nbsp;&nbsp;Google</span>
1625
1843
  </button>
1626
1844
  </div>
@@ -1630,12 +1848,12 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1630
1848
  </p>
1631
1849
  </div>
1632
1850
  </div>
1633
- `,s}function sn(r){const e=r,s=document.createElement("div");return s.id=K,s.innerHTML=`
1634
- <div class="__crossx-card __crossx-card--migration" style="${oe(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1851
+ `,s}function ro(r){const e=r,s=document.createElement("div");return s.id=ee,s.innerHTML=`
1852
+ <div class="__crossx-card __crossx-card--migration" style="${de(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1635
1853
  <div class="__crossx-header">
1636
1854
  <p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
1637
1855
  <p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
1638
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1856
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1639
1857
  </div>
1640
1858
  <hr class="__crossx-divider">
1641
1859
  <div class="__crossx-body">
@@ -1644,17 +1862,17 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1644
1862
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
1645
1863
  </div>
1646
1864
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
1647
- <span>${Uo(e.primary)}</span>
1865
+ <span>${Hn(e.primary)}</span>
1648
1866
  <span class="__crossx-recover-label">Recover My Wallet</span>
1649
1867
  </button>
1650
1868
  <button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
1651
1869
  </div>
1652
1870
  </div>
1653
- `,s}function rn(r,e){const s=r,{errorMessage:t,attemptCount:o,maxAttempts:n=5}=e??{},i=!!t,a=i?" --error":"",c=o!=null&&o>0?`<p class="__crossx-pin-attempt">${o}/${n}</p>`:"",l=o!=null&&o>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",u=document.createElement("div");return u.id=K,u.innerHTML=`
1654
- <div class="__crossx-card __crossx-card--migration" style="${oe(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1871
+ `,s}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>':"",d=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",h=document.createElement("div");return h.id=ee,h.innerHTML=`
1872
+ <div class="__crossx-card __crossx-card--migration" style="${de(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1655
1873
  <div class="__crossx-header">
1656
1874
  <p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
1657
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1875
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1658
1876
  </div>
1659
1877
  <hr class="__crossx-divider">
1660
1878
  <div class="__crossx-pin-center">
@@ -1670,11 +1888,11 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1670
1888
  ${d}
1671
1889
  </div>
1672
1890
  </div>
1673
- `,u}function on(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"],o=s[e.getDay()],n=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${o}, ${n} ${i} ${a}:${c}`}function nn(r,e,s){const t=r,o=e<=0,n=o?null:Date.now()+e*1e3,i=n?on(n):null,a=document.createElement("div");return a.id=K,a.innerHTML=`
1674
- <div class="__crossx-card __crossx-card--migration" style="${oe(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1891
+ `,h}function oo(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 io(r,e,s){const t=r,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?oo(o):null,a=document.createElement("div");return a.id=ee,a.innerHTML=`
1892
+ <div class="__crossx-card __crossx-card--migration" style="${de(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1675
1893
  <div class="__crossx-header">
1676
1894
  <p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
1677
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1895
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1678
1896
  </div>
1679
1897
  <hr class="__crossx-divider">
1680
1898
  <div class="__crossx-pin-center">
@@ -1685,131 +1903,70 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
1685
1903
  <div class="__crossx-pin-dot" aria-hidden="true">●</div>
1686
1904
  </div>
1687
1905
  <div class="__crossx-pin-lock-messages">
1688
- <p class="__crossx-pin-lock-message">${o?s:"Please try again after the lock expires."}</p>
1906
+ <p class="__crossx-pin-lock-message">${n?s:"Please try again after the lock expires."}</p>
1689
1907
  ${i?`<p class="__crossx-pin-lock-secondary">(Available from ${i})</p>`:""}
1690
1908
  </div>
1691
1909
  </div>
1692
1910
  </div>
1693
- `,{overlay:a,startCountdown:l=>{if(o||!n)return()=>{};const u=setInterval(()=>{Date.now()>=n&&(clearInterval(u),l())},1e3);return()=>clearInterval(u)}}}const Qe=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1694
- <path d="M15 12C15 13.6569 13.6569 15 12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12Z" fill="currentColor"/>
1695
- <path d="M21.8944 11.5528C19.7362 7.23635 15.9031 5 12 5C8.09687 5 4.26379 7.23635 2.10557 11.5528C1.96481 11.8343 1.96481 12.1657 2.10557 12.4472C4.26379 16.7637 8.09687 19 12 19C15.9031 19 19.7362 16.7637 21.8944 12.4472C22.0352 12.1657 22.0352 11.8343 21.8944 11.5528ZM12 17C9.03121 17 5.99806 15.3792 4.12966 12C5.99806 8.62078 9.03121 7 12 7C14.9688 7 18.0019 8.62078 19.8703 12C18.0019 15.3792 14.9688 17 12 17Z" fill="currentColor"/>
1696
- </svg>`,St=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1697
- <path d="M4.70711 3.29289C4.31658 2.90237 3.68342 2.90237 3.29289 3.29289C2.90237 3.68342 2.90237 4.31658 3.29289 4.70711L5.71706 7.13127C4.28639 8.20737 3.03925 9.68543 2.10557 11.5528C1.96481 11.8343 1.96481 12.1657 2.10557 12.4472C4.26379 16.7637 8.09687 19 12 19C13.5552 19 15.0992 18.645 16.5306 17.9448L19.2929 20.7071C19.6834 21.0976 20.3166 21.0976 20.7071 20.7071C21.0976 20.3166 21.0976 19.6834 20.7071 19.2929L4.70711 3.29289ZM15.0138 16.428C14.0343 16.8112 13.0134 17 12 17C9.03121 17 5.99806 15.3792 4.12966 12C4.94721 10.5214 5.98778 9.3794 7.14838 8.56259L9.29237 10.7066C9.10495 11.0982 9 11.5369 9 12C9 13.6569 10.3431 15 12 15C12.4631 15 12.9018 14.8951 13.2934 14.7076L15.0138 16.428Z" fill="currentColor"/>
1698
- <path d="M18.5523 13.8955C19.0353 13.3402 19.4784 12.7088 19.8703 12C18.0019 8.62078 14.9687 7 12 7C11.888 7 11.7759 7.00231 11.6637 7.00693L9.87939 5.22258C10.5774 5.07451 11.2875 5 12 5C15.9031 5 19.7362 7.23635 21.8944 11.5528C22.0352 11.8343 22.0352 12.1657 21.8944 12.4472C21.3504 13.5352 20.7 14.491 19.9689 15.3121L18.5523 13.8955Z" fill="currentColor"/>
1699
- </svg>`,an=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
1700
- <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"/>
1701
- </svg>`,et=`<svg width="9" height="7" viewBox="0 0 9 7" fill="none" xmlns="http://www.w3.org/2000/svg">
1702
- <path d="M1 3.5L3.5 6L8 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
1703
- </svg>`,cn=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
1704
- <path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
1705
- </svg>`,ln=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1706
- <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"/>
1707
- </svg>`;function dn(r){return{minLength:r.length>=8,uppercase:/[A-Z]/.test(r),number:/[0-9]/.test(r),special:/[^A-Za-z0-9]/.test(r)}}function un(r){return r.minLength&&r.uppercase&&r.number&&r.special}function hn(r){const s=[r.check1,r.check2,r.check3].map((t,o)=>`
1708
- <div class="__crossx-pw-notice-item" data-check-index="${o}" role="checkbox" aria-checked="false" tabindex="0">
1709
- <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${o}">${cn}</div>
1710
- <span class="__crossx-pw-notice-item-text">${T(t)}</span>
1911
+ `,{overlay:a,startCountdown:l=>{if(n||!o)return()=>{};const h=setInterval(()=>{Date.now()>=o&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function ao(r){const s=[r.check1,r.check2].map((t,n)=>`
1912
+ <div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
1913
+ <div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${uo}</div>
1914
+ <span class="__crossx-pw-notice-item-text">${B(t)}</span>
1711
1915
  </div>
1712
1916
  `).join("");return`
1713
1917
  <div class="__crossx-header">
1714
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${T(r.title)}</p>
1715
- <p class="__crossx-pw-subtitle">${T(r.headerSubtitle)}</p>
1716
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1918
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${B(r.title)}</p>
1919
+ <p class="__crossx-pw-subtitle">${B(r.headerSubtitle)}</p>
1920
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1717
1921
  </div>
1718
1922
  <hr class="__crossx-divider">
1719
1923
  <div class="__crossx-pw-body">
1720
1924
  <div class="__crossx-pw-fields __crossx-pw-fields--notice">
1721
1925
  <div class="__crossx-pw-notice-header">
1722
1926
  <div class="__crossx-pw-notice-title-row">
1723
- <span class="__crossx-pw-notice-icon">${ln}</span>
1724
- <p class="__crossx-pw-notice-title">${T(r.noticeTitle)}</p>
1927
+ <span class="__crossx-pw-notice-icon">${ho}</span>
1928
+ <p class="__crossx-pw-notice-title">${B(r.noticeTitle)}</p>
1725
1929
  </div>
1726
- <p class="__crossx-pw-notice-desc">${T(r.noticeDesc)}</p>
1930
+ <p class="__crossx-pw-notice-desc">${B(r.noticeDesc)}</p>
1727
1931
  </div>
1728
1932
  <div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
1729
1933
  ${s}
1730
1934
  </div>
1731
1935
  </div>
1732
- <button class="__crossx-pw-btn --disabled" id="__crossx-notice-submit" disabled
1733
- data-next-label="${T(r.nextButton)}"
1734
- data-submit-label="${T(r.submitButton)}">
1735
- ${T(r.nextButton)}
1936
+ <button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
1937
+ data-next-label="${B(r.nextButton)}"
1938
+ data-submit-label="${B(r.submitButton)}">
1939
+ ${B(r.nextButton)}
1736
1940
  </button>
1737
1941
  </div>
1738
1942
  <div class="__crossx-home-indicator"></div>
1739
- `}function pn(r,e){return`
1943
+ `}function bt(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">${B(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${B(r.subtitle)}</p>`:"",o=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${B(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">
1944
+ ${Ls}
1945
+ <span id="__crossx-pin6-lock-countdown"></span>
1946
+ </p>`:"",a=e?" --locked":"",c=Array.from({length:6},(l,d)=>`<input class="__crossx-pin6-box${a}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${d+1}"${e?" disabled":""}>`).join("");return`
1740
1947
  <div class="__crossx-header">
1741
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${T(r.title)}</p>
1742
- <p class="__crossx-pw-subtitle--tertiary">${T(r.subtitle)}</p>
1743
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1948
+ <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${B(r.title)}</p>
1949
+ ${t}
1950
+ <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
1744
1951
  </div>
1745
1952
  <hr class="__crossx-divider">
1746
- <div class="__crossx-pw-body">
1747
- <div class="__crossx-pw-fields __crossx-pw-fields--setup">
1748
- <div class="__crossx-pw-field-group __crossx-pw-fg--new">
1749
- <label class="__crossx-pw-label" for="__crossx-pw-new">${T(r.newPasswordLabel)}</label>
1750
- <div class="__crossx-pw-input-wrap" id="__crossx-pw-new-wrap">
1751
- <input class="__crossx-pw-input" id="__crossx-pw-new" type="password" autocomplete="new-password" />
1752
- <button class="__crossx-pw-toggle" id="__crossx-pw-new-toggle" type="button" aria-label="Toggle visibility">${Qe}</button>
1753
- </div>
1754
- </div>
1755
- <div class="__crossx-pw-rules" id="__crossx-pw-rules">
1756
- <div class="__crossx-pw-rule">
1757
- <div class="__crossx-pw-rule-dot" id="__crossx-rule-minLength">${et}</div>
1758
- <span class="__crossx-pw-rule-text">${T(r.rule_minLength)}</span>
1759
- </div>
1760
- <div class="__crossx-pw-rule">
1761
- <div class="__crossx-pw-rule-dot" id="__crossx-rule-uppercase">${et}</div>
1762
- <span class="__crossx-pw-rule-text">${T(r.rule_uppercase)}</span>
1763
- </div>
1764
- <div class="__crossx-pw-rule">
1765
- <div class="__crossx-pw-rule-dot" id="__crossx-rule-number">${et}</div>
1766
- <span class="__crossx-pw-rule-text">${T(r.rule_number)}</span>
1767
- </div>
1768
- <div class="__crossx-pw-rule">
1769
- <div class="__crossx-pw-rule-dot" id="__crossx-rule-special">${et}</div>
1770
- <span class="__crossx-pw-rule-text">${T(r.rule_special)}</span>
1771
- </div>
1772
- </div>
1773
- <div class="__crossx-pw-field-group __crossx-pw-fg--confirm">
1774
- <label class="__crossx-pw-label" for="__crossx-pw-confirm">${T(r.confirmPasswordLabel)}</label>
1775
- <div class="__crossx-pw-input-wrap" id="__crossx-pw-confirm-wrap">
1776
- <input class="__crossx-pw-input" id="__crossx-pw-confirm" type="password" autocomplete="new-password" />
1777
- <button class="__crossx-pw-toggle" id="__crossx-pw-confirm-toggle" type="button" aria-label="Toggle visibility">${Qe}</button>
1778
- </div>
1779
- <p class="__crossx-pw-error-text" id="__crossx-pw-confirm-error" style="display:none;">${T(r.confirmError)}</p>
1780
- ${e!=null&&e.errorMessage?`<p class="__crossx-pw-error-text">${T(e.errorMessage)}</p>`:""}
1781
- </div>
1953
+ <div class="__crossx-pin6-body"${s}>
1954
+ ${n}
1955
+ <div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
1956
+ ${c}
1782
1957
  </div>
1783
- <button class="__crossx-pw-btn --disabled" id="__crossx-pw-submit" disabled>
1784
- ${T(r.submitButton)}
1785
- </button>
1958
+ ${o}
1959
+ ${i}
1786
1960
  </div>
1787
1961
  <div class="__crossx-home-indicator"></div>
1788
- `}function fn(r,e,s,t){const o=r,n=document.createElement("div");n.id=K;const i=document.createElement("div");return i.className="__crossx-card __crossx-card--password",i.setAttribute("style",oe(o)),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-labelledby","__crossx-ttl"),i.innerHTML=hn(e),n.appendChild(i),n}function _n(r,e,s){var u;const t=r.querySelector("#__crossx-notice-submit"),o=Array.from(r.querySelectorAll(".__crossx-pw-notice-item")),n=new Set;t.removeAttribute("disabled");const i=t.dataset.nextLabel??"Next",a=t.dataset.submitLabel??"I Understand",c=()=>{const g=n.size===o.length;t.classList.toggle("--disabled",!g),t.textContent=g?a:i},l=(g,_)=>{if(n.has(_))return;const f=g.querySelector(`#__crossx-notice-check-${_}`);n.add(_),f.classList.add("--checked"),g.setAttribute("aria-checked","true"),c()},d=(g,_)=>{if(!n.has(_))return;const f=g.querySelector(`#__crossx-notice-check-${_}`);n.delete(_),f.classList.remove("--checked"),g.setAttribute("aria-checked","false"),c()};o.forEach(g=>{const _=parseInt(g.dataset.checkIndex??"0",10);g.addEventListener("click",()=>{n.has(_)?d(g,_):l(g,_)}),g.addEventListener("keydown",f=>{(f.key==="Enter"||f.key===" ")&&(f.preventDefault(),n.has(_)?d(g,_):l(g,_))})}),t.addEventListener("click",()=>{if(n.size===o.length){s();return}const g=o.find(f=>{const b=parseInt(f.dataset.checkIndex??"0",10);return!n.has(b)});if(!g)return;const _=parseInt(g.dataset.checkIndex??"0",10);g.scrollIntoView({behavior:"smooth",block:"nearest"}),g.classList.add("--highlight"),setTimeout(()=>{g.classList.remove("--highlight"),l(g,_)},400)}),(u=r.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",e)}function gn(r,e,s,t){var f;const o=r.querySelector("#__crossx-pw-new"),n=r.querySelector("#__crossx-pw-confirm"),i=r.querySelector("#__crossx-pw-new-toggle"),a=r.querySelector("#__crossx-pw-confirm-toggle"),c=r.querySelector("#__crossx-pw-confirm-wrap"),l=r.querySelector("#__crossx-pw-confirm-error"),d=r.querySelector("#__crossx-pw-submit"),u={minLength:r.querySelector("#__crossx-rule-minLength"),uppercase:r.querySelector("#__crossx-rule-uppercase"),number:r.querySelector("#__crossx-rule-number"),special:r.querySelector("#__crossx-rule-special")},g=()=>{const b=o.value,y=n.value,E=dn(b),D=un(E);Object.keys(E).forEach(_e=>{u[_e].classList.toggle("--met",E[_e])});const U=y.length>0,M=b===y,B=U&&!M;c.classList.toggle("--error",B),l.style.display=B?"block":"none";const j=D&&M&&y.length>0;d.disabled=!j,d.classList.toggle("--disabled",!j)},_=(b,y)=>{const E=b.type==="password";b.type=E?"text":"password",y.innerHTML=E?St:Qe};o.addEventListener("input",g),n.addEventListener("input",g),i.addEventListener("click",()=>_(o,i)),a.addEventListener("click",()=>_(n,a)),d.addEventListener("click",()=>{d.disabled||s(o.value)}),(f=r.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",t),o.addEventListener("keydown",b=>{b.key==="Escape"&&t()}),n.addEventListener("keydown",b=>{b.key==="Enter"&&!d.disabled&&s(o.value),b.key==="Escape"&&t()}),o.focus()}function xn(r,e,s){const t=r,o=!!(s!=null&&s.errorMessage),n=document.createElement("div");return n.id=K,n.innerHTML=`
1789
- <div class="__crossx-card __crossx-card--password" style="${oe(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1790
- <div class="__crossx-header">
1791
- <p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${T(e.title)}</p>
1792
- <p class="__crossx-pw-subtitle">${T(e.subtitle)}</p>
1793
- <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${te}</button>
1794
- </div>
1795
- <hr class="__crossx-divider">
1796
- <div class="__crossx-pw-body">
1797
- <div class="__crossx-pw-fields">
1798
- <div class="__crossx-pw-confirm-group${o?" --has-error":""}" id="__crossx-pw-confirm-group">
1799
- <div class="__crossx-pw-field-group">
1800
- <label class="__crossx-pw-label" for="__crossx-pw-enter">${T(e.passwordLabel)}</label>
1801
- <div class="__crossx-pw-input-wrap${o?" --error":""}" id="__crossx-pw-enter-wrap">
1802
- <span class="__crossx-pw-lock">${an}</span>
1803
- <input class="__crossx-pw-input" id="__crossx-pw-enter" type="password" autocomplete="current-password" />
1804
- <button class="__crossx-pw-toggle" id="__crossx-pw-enter-toggle" type="button" aria-label="Toggle visibility">${St}</button>
1805
- </div>
1806
- <p class="__crossx-pw-error-text" id="__crossx-pw-enter-error" style="${o?"":"display:none;"}">${o?T(s.errorMessage):""}</p>
1807
- </div>
1808
- <button class="__crossx-pw-btn --disabled" id="__crossx-pw-submit" disabled>
1809
- ${T(e.submitButton)}
1810
- </button>
1811
- </div>
1812
- </div>
1813
- </div>
1962
+ `}function Cs(r,e){const s=document.createElement("div");return s.id=ee,s.innerHTML=`
1963
+ <div class="__crossx-card __crossx-card--pin6" style="${de(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1964
+ ${e}
1814
1965
  </div>
1815
- `,n}function wn(r,e,s,t,o){var _;const n=r.querySelector("#__crossx-pw-enter"),i=r.querySelector("#__crossx-pw-enter-toggle"),a=r.querySelector("#__crossx-pw-enter-wrap"),c=r.querySelector("#__crossx-pw-enter-error"),l=r.querySelector("#__crossx-pw-confirm-group"),d=r.querySelector("#__crossx-pw-submit");n.addEventListener("input",()=>{const f=n.value.length>0;d.disabled=!f,d.classList.toggle("--disabled",!f),f&&(a.classList.remove("--error"),c.style.display="none",l.classList.remove("--has-error"))}),i.addEventListener("click",()=>{const f=n.type==="password";n.type=f?"text":"password",i.innerHTML=f?Qe:St});const u=f=>{c.textContent=f,c.style.display="",a.classList.add("--error"),l.classList.add("--has-error"),d.disabled=!1,d.classList.remove("--disabled")},g=()=>{if(d.disabled)return;const f=n.value;t?(d.disabled=!0,d.classList.add("--disabled"),t(f).then(b=>{b.ok?e(f):(u(b.error??"Incorrect password. Please try again."),n.focus())}).catch(b=>{o?o(b):s()})):e(f)};d.addEventListener("click",g),n.addEventListener("keydown",f=>{f.key==="Enter"&&g(),f.key==="Escape"&&s()}),(_=r.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",s),n.focus()}function mn(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((n,i)=>{n.addEventListener("input",()=>{const a=n.value.replace(/\D/g,"");n.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),n.addEventListener("keydown",a=>{a.key==="Backspace"&&!n.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),n.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),n.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((u,g)=>{t[g]&&(t[g].value=u)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(o=t[0])==null||o.focus()}class yn{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(o=>{var b;le();const n=[...e],i=Xo(n,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),o(y)},u=()=>{l(),o(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const E=y.dataset.walletAddress??"",D=parseInt(y.dataset.walletIndex??"0",10);d({address:E,index:D})})})})();const _=i.querySelector("#__crossx-add-wallet-btn");_&&_.addEventListener("click",async()=>{_.disabled=!0;try{const y=await s();n.push(y);const E=i.querySelector("#__crossx-wallet-list");if(E){const D=document.createElement("button");D.className="__crossx-wallet-item",D.dataset.walletIndex=String(y.index),D.dataset.walletAddress=y.address,D.innerHTML=`<span class="__crossx-wallet-addr">${Y(y.address)}</span>`,D.addEventListener("click",()=>d(y)),E.appendChild(D),D.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{_.disabled=!1}}),(b=i.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",u),i.addEventListener("click",y=>{y.target===i&&u()});const f=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)})}showLoginSelector(){return new Promise(e=>{var a,c,l;le();const s=tn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),o=d=>{t(),e(d)},n=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>o("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>o("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),s.addEventListener("click",d=>{d.target===s&&n()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",u=>u.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;le();const s=sn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),o=()=>{t(),e("recover")},n=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",n),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),s.addEventListener("click",d=>{d.target===s&&n()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showPasswordSetupPrompt(e){return new Promise(s=>{le();const t=this.messages,o={title:(t==null?void 0:t.passwordSetup_title)??"Create Password",headerSubtitle:(t==null?void 0:t.passwordNotice_headerSubtitle)??"Required for Transactions, PK/Mnemonic & Account Deletion.",noticeTitle:(t==null?void 0:t.passwordNotice_title)??"Password Setup Notice",noticeDesc:(t==null?void 0:t.passwordNotice_description)??"For your security, this password cannot be reset or recovered. Please ensure you have it backed up or memorized.",check1:(t==null?void 0:t.passwordNotice_check1)??"This password cannot be recovered if lost, and I have securely backed it up.",check2:(t==null?void 0:t.passwordNotice_check2)??"Losing this password may result in permanent loss of access to my account and all associated data.",check3:(t==null?void 0:t.passwordNotice_check3)??"No third party, including the support team, can recover or reset this password on my behalf.",nextButton:(t==null?void 0:t.passwordNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.passwordNotice_submitButton)??"I Understand"},n={title:(t==null?void 0:t.passwordSetup_title)??"Create Password",subtitle:(t==null?void 0:t.passwordSetup_subtitle)??"Password is only used to transfer your asset.",newPasswordLabel:(t==null?void 0:t.passwordSetup_newPasswordLabel)??"New Password",confirmPasswordLabel:(t==null?void 0:t.passwordSetup_confirmPasswordLabel)??"Confirm New Password",rule_minLength:(t==null?void 0:t.passwordSetup_rule_minLength)??"Over 8 letters",rule_uppercase:(t==null?void 0:t.passwordSetup_rule_uppercase)??"Include at least 1 uppercase letter",rule_number:(t==null?void 0:t.passwordSetup_rule_number)??"Include at least 1 number",rule_special:(t==null?void 0:t.passwordSetup_rule_special)??"Include at least 1 special character",confirmError:(t==null?void 0:t.passwordSetup_confirmError)??"Password is incorrect",submitButton:(t==null?void 0:t.passwordSetup_submitButton)??"Next"},i=fn(this.tokens,o),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=f=>{l(),s(f)},u=()=>{l(),s(null)},g=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",g),u())};document.addEventListener("keydown",g);const _=i.querySelector(".__crossx-card");_n(_,u,()=>{var f;_.innerHTML=pn(n,e),gn(i,{},d,u),(f=i.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",u)}),i.addEventListener("click",f=>{f.target===i&&u()})})}showPasswordInputPrompt(e){return new Promise((s,t)=>{le();const o=this.messages,n=(e==null?void 0:e.verifyMode)===!0,i={title:n?(o==null?void 0:o.verifyPassword_title)??"Verify Your Password":(o==null?void 0:o.passwordInput_title)??"Enter Password",subtitle:n?(o==null?void 0:o.verifyPassword_subtitle)??"To continue, please confirm your current password":(o==null?void 0:o.passwordInput_subtitle)??"Enter your password to continue.",passwordLabel:n?(o==null?void 0:o.verifyPassword_passwordLabel)??"Confirm Password":(o==null?void 0:o.passwordInput_passwordLabel)??"Password",submitButton:(o==null?void 0:o.passwordInput_submitButton)??"Confirm",error:(o==null?void 0:o.passwordInput_error)??"Incorrect password. Please try again."},a=xn(this.tokens,i,e),c=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},u=b=>{d(),s(b)},g=()=>{d(),s(null)},_=b=>{d(),t(b)};wn(a,u,g,e==null?void 0:e.onSubmit,_),a.addEventListener("click",b=>{b.target===a&&g()});const f=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",f),g())};document.addEventListener("keydown",f)})}showPinInputPrompt(e){return new Promise(s=>{var a;le();const t=rn(this.tokens,e);document.body.appendChild(t);const o=()=>t.remove(),n=c=>{o(),s(c)},i=()=>{o(),s(null)};mn(t,n,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showPinLockedPrompt(e,s){return new Promise(t=>{var l;le();const{overlay:o,startCountdown:n}=nn(this.tokens,e,s);document.body.appendChild(o);const i=()=>{c(),o.remove()},a=()=>{i(),t()},c=n(a);(l=o.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),o.addEventListener("click",d=>{d.target===o&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;le();const t=Ko(e,this.tokens);document.body.appendChild(t);const o=()=>t.remove(),n=()=>{o(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",n),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",n),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var g;d.stopPropagation();const u=l.dataset.copy;u&&((g=navigator.clipboard)==null||g.writeText(u).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&n()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{le();const o=jo(e,this.tokens);document.body.appendChild(o);const n=()=>o.remove();let i=!1;const a=()=>{i||(i=!0,n(),t())},c=()=>{var d,u;(d=o.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(u=o.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),o.addEventListener("click",g=>{g.target===o&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(zo(o,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;le();let t;e.type==="sign-message"?t=Jo(e,this.tokens):e.type==="sign-typed-data"?t=Yo(e,this.tokens):e.type==="sign"?t=Go(e,this.tokens):t=Wo(e,this.tokens),document.body.appendChild(t);const o=()=>t.remove(),n=()=>{o(),s(!0)},i=()=>{o(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",n),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(u=>{u.addEventListener("click",g=>{var f;g.stopPropagation();const _=u.dataset.copy;_&&((f=navigator.clipboard)==null||f.writeText(_).catch(()=>{}))})}),t.addEventListener("click",u=>{u.target===t&&i()});const a=u=>{u.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class bn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function vn(r){r.debug;const e=Ue.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},n=s.authMode!=="cookie"&&Dt.isAvailable()?new Dt:new rr,i=new Co,a=new Po,c=new mt,l=new bn,d=new Rt;let u;r.useMockWallet?(h.log("[CROSSx] Mock Wallet Provider 사용"),u=new No(n,d)):(h.log("[CROSSx] Remote Wallet Provider 사용"),u=new Ze(t,n,a,l,d));const g=new De(t,a),_=new yn(r.theme??"light",r.themeTokens);return new Fe(s,t,n,i,a,c,u,l,_,g,d)}return Q.CROSSxError=m,Q.CROSSxEthereumProvider=Et,Q.CROSSxSDK=Fe,Q.ChainId=Ms,Q.ErrorCode=p,Q.createCROSSxSDK=vn,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"}),Q}({});
1966
+ `,s}function co(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 lo(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 vt(r,e,s,t,n,o){let i=!!(o&&o>Date.now()),a=!1;const c=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),l=()=>r.querySelector("#__crossx-pin6-boxes"),d=()=>r.querySelector("#__crossx-pin6-error"),h=()=>r.querySelector("#__crossx-pin6-lock-msg"),m=()=>r.querySelector("#__crossx-pin6-lock-countdown"),x=()=>r.querySelector(".__crossx-pin6-body"),w=()=>c().map(v=>v.value).join(""),I=v=>{i=v,c().forEach(P=>{P.disabled=v,P.classList.toggle("--locked",v)})},y=()=>{const v=d();v&&(v.textContent="")},S=v=>{const P=d();P&&(P.textContent=v);const N=l();N==null||N.classList.add("--shake"),setTimeout(()=>N==null?void 0:N.classList.remove("--shake"),500),c().forEach(W=>{W.value=""}),setTimeout(()=>{var W;return(W=c()[0])==null?void 0:W.focus()},50)},C=v=>{var G;I(!0),c().forEach(q=>{q.value=""});const P=d();if(P&&(P.textContent="Too many failed attempts. Please wait."),!h()){const q=document.createElement("p");q.className="__crossx-pin6-lock-msg",q.id="__crossx-pin6-lock-msg",q.innerHTML=`${Ls}<span id="__crossx-pin6-lock-countdown"></span>`;const D=d();D?D.insertAdjacentElement("afterend",q):(G=x())==null||G.appendChild(q)}const N=()=>{var R;const q=v-Date.now(),D=m();q<=0?(clearInterval(W),I(!1),(R=h())==null||R.remove(),P&&(P.textContent=""),setTimeout(()=>{var k;return(k=c()[0])==null?void 0:k.focus()},50)):D&&(D.textContent=` ${lo(q)}`)},W=setInterval(N,1e3);N();const J=new MutationObserver(()=>{document.contains(r)||(clearInterval(W),J.disconnect())});J.observe(document.body,{childList:!0,subtree:!1})},U=async()=>{if(i||a)return;const v=w();if(v.length===6){a=!0,c().forEach(P=>{P.disabled=!0});try{if(n){const P=await n(v);P.ok?e(v):P.lockExpiresAt?C(P.lockExpiresAt):S(P.error??"Incorrect PIN. Please try again.")}else e(v)}catch(P){t&&t(P)}finally{a=!1,i||c().forEach(P=>{P.disabled=!1})}}};o&&o>Date.now()?C(o):setTimeout(()=>{var v;return(v=c()[0])==null?void 0:v.focus()},100),c().forEach((v,P)=>{v.addEventListener("input",()=>{var W;const N=v.value.replace(/\D/g,"").slice(-1);v.value=N,y(),N&&P<5&&((W=c()[P+1])==null||W.focus()),w().length===6&&setTimeout(U,80)}),v.addEventListener("keydown",N=>{var W,J;if(N.key==="Backspace"){if(N.preventDefault(),v.value)v.value="";else if(P>0){const G=c()[P-1];G.value="",G.focus()}}else N.key==="ArrowLeft"&&P>0?(N.preventDefault(),(W=c()[P-1])==null||W.focus()):N.key==="ArrowRight"&&P<5?(N.preventDefault(),(J=c()[P+1])==null||J.focus()):N.key==="Escape"&&s()}),v.addEventListener("paste",N=>{var G,q;N.preventDefault();const W=(((G=N.clipboardData)==null?void 0:G.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!W)return;const J=c();W.split("").forEach((D,R)=>{J[R]&&(J[R].value=D)}),(q=J[Math.min(W.length-1,5)])==null||q.focus(),y(),w().length===6&&setTimeout(U,80)}),v.addEventListener("focus",()=>v.select())})}const Ls=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
1967
+ <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"/>
1968
+ </svg>`,uo=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
1969
+ <path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
1970
+ </svg>`,ho=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1971
+ <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"/>
1972
+ </svg>`;function po(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((h,m)=>{t[m]&&(t[m].value=h)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class fo{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Ps(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Ps(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var I;pe();const o=[...e],i=Qn(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const S=y.dataset.walletAddress??"",C=parseInt(y.dataset.walletIndex??"0",10);d({address:S,index:C})})})})();const x=i.querySelector("#__crossx-add-wallet-btn");x&&x.addEventListener("click",async()=>{x.disabled=!0;try{const y=await s();o.push(y);const S=i.querySelector("#__crossx-wallet-list");if(S){const C=document.createElement("button");C.className="__crossx-wallet-item",C.dataset.walletIndex=String(y.index),C.dataset.walletAddress=y.address,C.innerHTML=`<span class="__crossx-wallet-addr">${te(y.address)}</span>`,C.addEventListener("click",()=>d(y)),S.appendChild(C),C.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{x.disabled=!1}}),(I=i.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(){return new Promise(e=>{var a,c,l;pe();const s=so(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",h=>h.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;pe();const s=ro(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinSetupPrompt(e){return new Promise(s=>{pe();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=Cs(this.tokens,ao(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=C=>{d(),s(C)},m=()=>{d(),s(null)},x=a.querySelector(".__crossx-card"),w={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."},I=C=>{var U;x.innerHTML=bt({title:i.title,headerSubtitle:i.headerSubtitle}),(U=x.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",m),vt(x,v=>{v===C?h(C):y(o.mismatchError)},m)},y=C=>{var U;x.innerHTML=bt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:C}),(U=x.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",m),vt(x,v=>{const P=co(v,w);P?y(P):I(v)},m)};(()=>{var q;const C=Array.from(x.querySelectorAll(".__crossx-pw-notice-item")),U=x.querySelector("#__crossx-pin-notice-next"),v=new Set;U.removeAttribute("disabled");const P=U.dataset.nextLabel??"Next",N=U.dataset.submitLabel??"I Understand",W=()=>{const D=v.size===C.length;U.classList.toggle("--disabled",!D),U.textContent=D?N:P},J=(D,R)=>{if(v.has(R))return;const k=D.querySelector(`#__crossx-notice-check-${R}`);v.add(R),k.classList.add("--checked"),D.setAttribute("aria-checked","true"),W()},G=(D,R)=>{if(!v.has(R))return;const k=D.querySelector(`#__crossx-notice-check-${R}`);v.delete(R),k.classList.remove("--checked"),D.setAttribute("aria-checked","false"),W()};C.forEach(D=>{const R=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{v.has(R)?G(D,R):J(D,R)}),D.addEventListener("keydown",k=>{(k.key===" "||k.key==="Enter")&&(k.preventDefault(),v.has(R)?G(D,R):J(D,R))})}),U.addEventListener("click",()=>{if(v.size===C.length){y(e==null?void 0:e.errorMessage);return}const D=C.find(k=>{const _=parseInt(k.dataset.checkIndex??"0",10);return!v.has(_)});if(!D)return;const R=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),J(D,R)},400)}),(q=x.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",m)})(),a.addEventListener("click",C=>{C.target===a&&m()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;pe();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=Cs(this.tokens,bt({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt})),l=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(c);let d=!1;const h=()=>{d||(d=!0,c.remove(),document.body.style.overflow=l)},m=S=>{h(),s(S)},x=()=>{h(),s(null)},w=S=>{h(),t(S)},I=c.querySelector(".__crossx-card");(y=I.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",x),vt(I,m,x,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",S=>{S.target===c&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;pe();const t=no(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};po(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;pe();const{overlay:n,startCountdown:o}=io(this.tokens,e,s);document.body.appendChild(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",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;pe();const t=Jn(e,this.tokens);document.body.appendChild(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",d=>{var m;d.stopPropagation();const h=l.dataset.copy;h&&((m=navigator.clipboard)==null||m.writeText(h).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=>{pe();const n=zn(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,h;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",m=>{m.target===n&&a()});const l=m=>{m.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 c,l,d;pe();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=Gn(e,this.tokens):t=qn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",m=>{var w;m.stopPropagation();const x=h.dataset.copy;x&&((w=navigator.clipboard)==null||w.writeText(x).catch(()=>{}))})}),t.addEventListener("click",h=>{h.target===t&&i()});const a=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class _o{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function go(r){r.debug;const e=We.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},o=s.authMode!=="cookie"&&Lt.isAvailable()?new Lt:new nr,i=new kn,a=new Cn,c=new Se,l=new _o,d=new At;let h;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),h=new Ln(o,d)):(u.log("[CROSSx] Remote Wallet Provider 사용"),h=new Be(t,o,a,l,d));const m=new Ue(t,a),x=new fo(r.theme??"light",r.themeTokens);return new Ge(s,t,o,i,a,c,h,l,x,m,d)}return ne.CROSSxError=f,ne.CROSSxEthereumProvider=St,ne.CROSSxSDK=Ge,ne.ChainId=$s,ne.ErrorCode=p,ne.createCROSSxSDK=go,Object.defineProperty(ne,Symbol.toStringTag,{value:"Module"}),ne}({});