@nexus-cross/crossx-sdk-core 1.3.9 → 1.3.11
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.
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +4 -0
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts +10 -3
- package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
- package/dist/core/i18n/messages.en.d.ts.map +1 -1
- package/dist/core/i18n/messages.ko.d.ts.map +1 -1
- package/dist/core/i18n/types.d.ts +13 -0
- package/dist/core/i18n/types.d.ts.map +1 -1
- package/dist/core/ports/ConfirmationPort.d.ts +8 -1
- package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
- package/dist/core/types/errors.d.ts +4 -0
- package/dist/core/types/errors.d.ts.map +1 -1
- package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
- package/dist/crossx.global +151 -91
- package/dist/index.cjs +147 -87
- package/dist/index.js +1331 -1072
- package/dist/sdk/CROSSxSDK.d.ts +38 -0
- package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/crossx.global
CHANGED
|
@@ -1,8 +1,18 @@
|
|
|
1
|
-
var CROSSx=function(Z){"use strict";var Fi=Object.defineProperty;var Ki=(Z,f,m)=>f in Z?Fi(Z,f,{enumerable:!0,configurable:!0,writable:!0,value:m}):Z[f]=m;var E=(Z,f,m)=>Ki(Z,typeof f!="symbol"?f+"":f,m);var gt,Cs;var f=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(f||{});class m extends Error{constructor(e,r,t){super(r),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 Ze={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Ls=Object.fromEntries(Object.entries(Ze).map(([s,e])=>[s,e.caipId])),Ds=new Map(Object.values(Ze).map(s=>[s.caipId,s]));new Map(Object.values(Ze).map(s=>[s.chainId,s]));const Ms={symbol:"",decimals:18};function xt(s){var e;return((e=Ds.get(s))==null?void 0:e.nativeCurrency)??Ms}class Xt{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new m(f.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(f.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let be=null;function Gi(s){}function Zt(s){be=s}const d={info(...s){if(be){be.log(...s);return}console.log(...s)},log(...s){if(be){be.log(...s);return}},warn(...s){if(be){be.warn(...s);return}},error(...s){if(be){be.error(...s);return}}},$s={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",alert_sessionExpired:"인증이 만료되었습니다. 확인을 누른 뒤 다시 로그인해 주세요."},Qt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",alert_sessionExpired:"Your session has expired. Tap OK and sign in again."},Ws={ko:$s,en:Qt};function mt(s="en",e){return Ws[s]??Qt}const er="crossx_access_token",tr="crossx_refresh_token",rr="crossx_user_info";class Us{constructor(e,r,t,n,o,i,a){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,r){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new m(f.AUTH_FAILED,`${r} 실패 (코드 ${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 m(f.AUTH_FAILED,`${r} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){let r;try{const t=e==null?void 0:e.provider;let n="/login";t==="google"?n="/google":t==="apple"&&(n="/apple");const{oauthServiceUrl:o}=this.config,i=`${o}${n}`;d.log(`[CROSSx] OAuth 팝업 열기 (${t||"일반"} 로그인)`),r=await this.oauth.openAuth({authUrl:i,expectedOrigin:new URL(o).origin}),d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")")}catch(t){return d.error("[CROSSx] SignIn 에러 (OAuth 단계):",t),{success:!1,error:t instanceof Error?t.message:"Sign in failed"}}return this.processFirebaseToken(r)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e){var n,o,i,a;let r,t=!1;try{const{authApiUrl:c}=this.config,{accessToken:l,refreshToken:u}=await this.exchangeFirebaseToken(e,c);let h,_;try{const w=this.crypto.decodeJWT(e);_=(n=w.firebase)==null?void 0:n.sign_in_provider;const b=((o=w.firebase)==null?void 0:o.identities)??{};_==="google.com"?h=(i=b["google.com"])==null?void 0:i[0]:_==="apple.com"&&(h=(a=b["apple.com"])==null?void 0:a[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",_,"hasProviderSub:",!!h)}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(l){const w=this.crypto.decodeJWT(l);d.log("[CROSSx] access_token 디코딩 — sub:",w.sub,"exp:",w.exp);const b=await this.crypto.verifyJWT(l);if(t=b.signatureVerified??!1,!b.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const y=b.payload;r={id:y.sub,email:y.email,signInProvider:_,providerSub:h},this.tokenStore.set(l),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l),u&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u):u&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const w=this.crypto.decodeJWT(e);r={id:w.sub,email:w.email,signInProvider:_,providerSub:h},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",r.id)}d.log("[CROSSx] 사용자 정보 — id:",r.id);const p=this.useCookieAuth?{id:r.id,signInProvider:r.signInProvider,providerSub:r.providerSub}:r;await this.storage.set(this.STORAGE_KEY_USER,p),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,t)}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new m(f.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const 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 r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){return d.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,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"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new m(f.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,c);const l=this.extractRefreshToken(a);l&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,l)}return d.log("[CROSSx] silentRefresh 성공"),c}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(rr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(er);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(tr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(rr),await this.storage.remove(er),await this.storage.remove(tr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof m&&o.code===f.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof m&&(o.code===f.PROJECT_NOT_REGISTERED||o.code===f.PROJECT_ID_MISSING||o.code===f.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}}class Hs{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Bs{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new m(f.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class wt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r[o]^t[o];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Fs{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new m(f.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Ks{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}var Qe={environment:"production"};const et={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 Gs(s){const e=s.environment;return e&&e in et?et[e]:null}function qs(){try{if(typeof Qe<"u"){const s=typeof Qe=="string"?JSON.parse(Qe):Qe,e=Gs(s);if(e)return e}}catch{}return et.production}const Js=2e3,sr=6e4,Vs=1e3,zs=1e4,Ys="0x77359400",nr="0x3B9ACA00",or=130,ir=6,ar=18,js=3e4,Xs=5*60*1e3,Zs=30*1e3,ae=class ae extends Ks{constructor(e,r,t,n,o,i,a,c,l,u,h){var _,p;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._themeMediaCleanup=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&Zt(e.logger),this.confirmation=l,this.pinStore=h??new wt,this.chainRegistry=u,this.jsonRpc=new Fs(u,o),this.signInUseCase=new Us(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Hs(this.internalConfig,t,c),this.migrateWalletUseCase=new Bs(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v1.3.9 초기화 중..."),this.confirmation.setMessages(mt(this._config.locale));try{const n=qs();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const o=await this.signInUseCase.restoreSession();if(o!=null&&o.success){this.applyAuthResult(o);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(i){if(!(i instanceof m&&i.code===f.PIN_CANCELLED))throw i;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.3.9 초기화 완료"),this.emit("initialized",{restored:!!(o!=null&&o.success)}),o??null}catch(n){throw new m(f.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new m(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new m(f.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};r={...e,provider:t}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(f.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const r=await this.signIn(e);if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...r,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof m&&t.code===f.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new m(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithOAuthToken(e);return r.success&&this.applyAuthResult(r),r}catch(r){throw new m(f.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",r)}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new m(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(f.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(f.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof m&&r.code===f.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof m?r:new m(f.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(f.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 m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.walletProvider.getAddresses(this.userId);r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.ensurePinForSigning();const n=r.length,i={address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,n))).address,index:n};return r.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 m?e:new m(f.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof m?r:new m(f.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const o=n?"dark":"light";this.applyTheme(o,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(mt(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const r=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",r);const t=await this.handleMigrationFlow(r);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new m(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const r=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof m&&r.code===f.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new m(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}await this.ensurePinSetup();try{const r=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof m&&r.code===f.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new m(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(f.USER_REJECTED,"User rejected the message signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof m?i:new m(f.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new m(f.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ae.validateTypedDataChainId(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(f.USER_REJECTED,"User rejected the typed data signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return ae.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof m?i:new m(f.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(ae.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=xt(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(f.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return ae.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(f.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new m(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=xt(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(f.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(f.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??Vs,o=zs,i=t.timeoutMs??sr,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,o)}throw new m(f.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var b,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,r,i),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Js,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??sr,u=xt(e),h=r.from??"";let _,p;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(A=>{_=A;const N=BigInt(A.gasUsed)*BigInt(A.effectiveGasPrice),K=r.value?BigInt(r.value):0n,W=ae.formatTxAmount(r.value,u.symbol,u.decimals),Y=ae.formatTxAmount("0x"+N.toString(16),u.symbol,u.decimals),G=ae.formatTxAmount("0x"+(K+N).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:A.from,to:A.to??r.to,amount:W,fees:Y,total:G,nativeSymbol:u.symbol,status:A.status==="0x1"?"success":"reverted"}}).catch(A=>(p=A instanceof Error?A:new Error(String(A)),{chainId:e,txHash:a,from:h,to:r.to,amount:ae.formatTxAmount(r.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:r.to},w),p)throw p;return{chainId:e,txHash:a,receipt:_}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new m(f.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof m?n:new m(f.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new m(f.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const o=n instanceof Error?n.message:String(n);throw new m(f.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new m(f.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new m(f.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof m)throw t;const n=t instanceof Error?t.message:String(t);throw new m(f.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:ae.formatWei(n),chainId:e}}catch(t){if(t instanceof m)throw t;const n=t instanceof Error?t.message:String(t);throw new m(f.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const r=BigInt(e);if(r===0n)return"0";const t=10n**BigInt(ar),n=r/t,i=(r%t).toString().padStart(ar,"0").replace(/0+$/,"").slice(0,ir);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Xt(this,e)}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof m)throw n;const o=n instanceof Error?n.message:String(n);throw new m(f.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,r,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,ir).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${r}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const h=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});if(h===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const _=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,h,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const p=_.pinStatus;if(i=p.maxAttempts,o=i-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const w=p.lockExpiresAt*1e3,b=Math.max(1,Math.round((w-Date.now())/1e3)),y=b<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${b}초, 메시지: ${y}`),await this.confirmation.showRecoveryPinLockedPrompt(b,y),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof m))throw _;if(_.code===f.MIGRATION_PIN_LOCKED){const p=_.details;if(i=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((p==null?void 0:p.lockExpiresAt)??0)*1e3,b=Math.max(1,Math.round((w-Date.now())/1e3)),y=b<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${b}초`),await this.confirmation.showRecoveryPinLockedPrompt(b,y),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const h=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof m&&h.code===f.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}async withResolvedGasAndFee(e,r){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,h,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],r):null,o?this.estimateGas(e,r):null,i?this.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=h,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const p=_;if(p){const w=nr;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(w)).toString(16),c.maxPriorityFeePerGas=w,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Ys,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=nr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,r){const t=ae.extractDomainChainId(r);if(e==="0"){if(t!==void 0&&t!==0)throw new m(f.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 m(f.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new m(f.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const r=e.domain;if(r==null||typeof r!="object")return;const t=r.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new m(f.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(r.length!==or)throw new m(f.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${or} hex 문자(65 바이트) 예상, 현재 ${r.length}`)}static validateSignedTxFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new m(f.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(r.length<2)throw new m(f.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new m(f.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof m)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var r,t,n,o;this.authenticated=e.success,this.userId=((r=e.user)==null?void 0:r.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=ae.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&&(d.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 m(f.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const r=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new m(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.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:r});if(!i)throw new m(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}const o=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(d.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 m){if(c.code===f.PIN_WRONG)return{ok:!1,error:"Incorrect PIN. Please try again."};if(c.code===f.PIN_INVALID)return{ok:!1,error:c.message};if(c.code===f.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}}});if(!o)throw new m(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(o),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),t()}catch(o){if(o instanceof m&&(o.code===f.AUTH_NOT_AUTHENTICATED||o.code===f.AUTH_TOKEN_EXPIRED)){const{alert_sessionExpired:i}=mt(this._config.locale??"en");typeof globalThis.alert=="function"&&globalThis.alert(i)}throw n(o),o}finally{this._verifyPinMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const r=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",r),r!=="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,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let r,t;try{return await e()}catch(n){if(n instanceof m)if(n.code===f.PIN_WRONG)r="Incorrect PIN. Please enter your current PIN.";else if(n.code===f.PIN_INVALID)r=n.message;else if(n.code===f.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,r="Too many failed attempts. Your account is temporarily locked."}else throw n;else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",r),this.pinStore.clear(),await this.ensureVerifiedPin(r,t),t=void 0;try{return await e()}catch(n){if(n instanceof m){if(n.code===f.PIN_WRONG){r="Incorrect PIN. Please try again.";continue}if(n.code===f.PIN_INVALID){r=n.message;continue}if(n.code===f.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,r="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 m(f.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 m(f.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(f.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Zt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};ae.OFFCHAIN_CHAIN_ID="0";let tt=ae;class Qs{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const yt="crossx-sdk",en=1,pe="data",ke="keys",rt="aes-primary",tn=12;class cr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,en);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(pe)||o.createObjectStore(pe),o.objectStoreNames.contains(ke)||o.createObjectStore(ke)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(r);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,r,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(r);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((r,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>r(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(ke,rt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(ke,rt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===yt)return null;try{const e=await this.openDB(yt),r=e.transaction([ke,pe],"readonly"),t=r.objectStore(ke).get(rt),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=r.objectStore(pe).getAll(),i=r.objectStore(pe).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(ke,rt,n);for(let l=0;l<c.length;l++)await this.idbPut(pe,String(c[l]),a[l]);return indexedDB.deleteDatabase(yt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(tn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(pe,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(pe,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(pe,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(pe)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const bt=crypto,lr=s=>s instanceof CryptoKey,st=new TextEncoder,qe=new TextDecoder;function rn(...s){const e=s.reduce((n,{length:o})=>n+o,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const sn=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Te=s=>{let e=s;e instanceof Uint8Array&&(e=qe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return sn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Q extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Q.code="ERR_JOSE_GENERIC";class he extends Q{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class St extends Q{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}St.code="ERR_JWT_EXPIRED";class dr extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}dr.code="ERR_JOSE_ALG_NOT_ALLOWED";class _e extends Q{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}_e.code="ERR_JOSE_NOT_SUPPORTED";class nn extends Q{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}nn.code="ERR_JWE_DECRYPTION_FAILED";class on extends Q{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}on.code="ERR_JWE_INVALID";class j extends Q{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}j.code="ERR_JWS_INVALID";class ge extends Q{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ge.code="ERR_JWT_INVALID";class an extends Q{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}an.code="ERR_JWK_INVALID";class vt extends Q{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}vt.code="ERR_JWKS_INVALID";class Et extends Q{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Et.code="ERR_JWKS_NO_MATCHING_KEY";class ur extends Q{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}ur.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class hr extends Q{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}hr.code="ERR_JWKS_TIMEOUT";class fr extends Q{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}fr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function xe(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function Je(s,e){return s.name===e}function It(s){return parseInt(s.name.slice(4),10)}function cn(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function ln(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function dn(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!Je(s.algorithm,"HMAC"))throw xe("HMAC");const t=parseInt(e.slice(2),10);if(It(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Je(s.algorithm,"RSASSA-PKCS1-v1_5"))throw xe("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(It(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Je(s.algorithm,"RSA-PSS"))throw xe("RSA-PSS");const t=parseInt(e.slice(2),10);if(It(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw xe("Ed25519 or Ed448");break}case"Ed25519":{if(!Je(s.algorithm,"Ed25519"))throw xe("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Je(s.algorithm,"ECDSA"))throw xe("ECDSA");const t=cn(e);if(s.algorithm.namedCurve!==t)throw xe(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}ln(s,r)}function pr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const _r=(s,...e)=>pr("Key must be ",s,...e);function gr(s,e,...r){return pr(`Key for the ${s} algorithm must be `,e,...r)}const xr=s=>lr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",nt=["CryptoKey"],un=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const o of n){if(r.has(o))return!1;r.add(o)}}return!0};function hn(s){return typeof s=="object"&&s!==null}function Se(s){if(!hn(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const fn=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Me(s){return Se(s)&&typeof s.kty=="string"}function pn(s){return s.kty!=="oct"&&typeof s.d=="string"}function _n(s){return s.kty!=="oct"&&typeof s.d>"u"}function gn(s){return Me(s)&&s.kty==="oct"&&typeof s.k=="string"}function xn(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new _e('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const mr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=xn(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,bt.subtle.importKey("jwk",n,...t)},wr=s=>Te(s);let $e,We;const yr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ot=async(s,e,r,t,n=!1)=>{let o=s.get(e);if(o!=null&&o[t])return o[t];const i=await mr({...r,alg:t});return n&&Object.freeze(e),o?o[t]=i:s.set(e,{[t]:i}),i},mn={normalizePublicKey:(s,e)=>{if(yr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?wr(r.k):(We||(We=new WeakMap),ot(We,s,r,e))}return Me(s)?s.k?Te(s.k):(We||(We=new WeakMap),ot(We,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(yr(s)){let r=s.export({format:"jwk"});return r.k?wr(r.k):($e||($e=new WeakMap),ot($e,s,r,e))}return Me(s)?s.k?Te(s.k):($e||($e=new WeakMap),ot($e,s,s,e,!0)):s}};async function br(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Te(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new _e('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return mr({...s,alg:e});default:throw new _e('Unsupported "kty" (Key Type) Parameter value')}}const Ue=s=>s==null?void 0:s[Symbol.toStringTag],At=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},wn=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Me(e)){if(gn(e)&&At(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!xr(e))throw new TypeError(gr(s,e,...nt,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Ue(e)} instances for symmetric algorithms must be of type "secret"`)}},yn=(s,e,r,t)=>{if(t&&Me(e))switch(r){case"sign":if(pn(e)&&At(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(_n(e)&&At(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!xr(e))throw new TypeError(gr(s,e,...nt,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Ue(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${Ue(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${Ue(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${Ue(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${Ue(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Sr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?wn(e,r,t,s):yn(e,r,t,s)}Sr.bind(void 0,!1);const vr=Sr.bind(void 0,!0);function bn(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(i=>typeof i!="string"||i.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...e.entries()]):o=e;for(const i of t.crit){if(!o.has(i))throw new _e(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new s(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&t[i]===void 0)throw new s(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(t.crit)}const Sn=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function vn(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new _e(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function En(s,e,r){if(e=await mn.normalizePublicKey(e,s),lr(e))return dn(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(_r(e,...nt));return bt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(_r(e,...nt,"Uint8Array","JSON Web Key"))}const In=async(s,e,r,t)=>{const n=await En(s,e,"verify");fn(s,n);const o=vn(s,n.algorithm);try{return await bt.subtle.verify(o,n,r,t)}catch{return!1}};async function An(s,e,r){if(!Se(s))throw new j("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new j('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new j("JWS Protected Header incorrect type");if(s.payload===void 0)throw new j("JWS Payload missing");if(typeof s.signature!="string")throw new j("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new j("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const b=Te(s.protected);t=JSON.parse(qe.decode(b))}catch{throw new j("JWS Protected Header is invalid")}if(!un(t,s.header))throw new j("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},o=bn(j,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let i=!0;if(o.has("b64")&&(i=t.b64,typeof i!="boolean"))throw new j('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new j('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&Sn("algorithms",r.algorithms);if(c&&!c.has(a))throw new dr('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof s.payload!="string")throw new j("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new j("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,vr(a,e,"verify"),Me(e)&&(e=await br(e,a))):vr(a,e,"verify");const u=rn(st.encode(s.protected??""),st.encode("."),typeof s.payload=="string"?st.encode(s.payload):s.payload);let h;try{h=Te(s.signature)}catch{throw new j("Failed to base64url decode the signature")}if(!await In(a,e,h,u))throw new fr;let p;if(i)try{p=Te(s.payload)}catch{throw new j("Failed to base64url decode the payload")}else typeof s.payload=="string"?p=st.encode(s.payload):p=s.payload;const w={payload:p};return s.protected!==void 0&&(w.protectedHeader=t),s.header!==void 0&&(w.unprotectedHeader=s.header),l?{...w,key:e}:w}async function Tn(s,e,r){if(s instanceof Uint8Array&&(s=qe.decode(s)),typeof s!="string")throw new j("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:o,length:i}=s.split(".");if(i!==3)throw new j("Invalid Compact JWS");const a=await An({payload:n,protected:t,signature:o},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Rn=s=>Math.floor(s.getTime()/1e3),Er=60,Ir=Er*60,Tt=Ir*24,Pn=Tt*7,On=Tt*365.25,Cn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ar=s=>{const e=Cn.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Er);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Ir);break;case"day":case"days":case"d":n=Math.round(r*Tt);break;case"week":case"weeks":case"w":n=Math.round(r*Pn);break;default:n=Math.round(r*On);break}return e[1]==="-"||e[4]==="ago"?-n:n},Tr=s=>s.toLowerCase().replace(/^application\//,""),kn=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Nn=(s,e,r={})=>{let t;try{t=JSON.parse(qe.decode(e))}catch{}if(!Se(t))throw new ge("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Tr(s.typ)!==Tr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:o=[],issuer:i,subject:a,audience:c,maxTokenAge:l}=r,u=[...o];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),i!==void 0&&u.push("iss");for(const w of new Set(u.reverse()))if(!(w in t))throw new he(`missing required "${w}" claim`,t,w,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!kn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=Ar(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=r,p=Rn(_||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>p+h)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=p-h)throw new St('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const w=p-t.iat,b=typeof l=="number"?l:Ar(l);if(w-h>b)throw new St('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(w<0-h)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Ln(s,e,r){var i;const t=await Tn(s,e,r);if((i=t.protectedHeader.crit)!=null&&i.includes("b64")&&t.protectedHeader.b64===!1)throw new ge("JWTs MUST NOT use unencoded payload");const o={payload:Nn(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...o,key:t.key}:o}function Dn(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new _e('Unsupported "alg" value for a JSON Web Key Set')}}function Mn(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every($n)}function $n(s){return Se(s)}function Rr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Wn{constructor(e){if(this._cached=new WeakMap,!Mn(e))throw new vt("JSON Web Key Set malformed");this._jwks=Rr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},o=Dn(t),i=this._jwks.keys.filter(l=>{let u=o===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=i;if(c===0)throw new Et;if(c!==1){const l=new ur,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const h of i)try{yield await Pr(u,h,t)}catch{}},l}return Pr(this._cached,a,t)}}async function Pr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await br({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new vt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function Or(s){const e=new Wn(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Rr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Un=async(s,e,r)=>{let t,n,o=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{o=!0,t.abort()},e));const i=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw o?new hr:a});if(n!==void 0&&clearTimeout(n),i.status!==200)throw new Q("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new Q("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Hn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Rt;(typeof navigator>"u"||!((Cs=(gt=navigator.userAgent)==null?void 0:gt.startsWith)!=null&&Cs.call(gt,"Mozilla/5.0 ")))&&(Rt="jose/v5.10.0");const Pt=Symbol();function Bn(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Fn{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Pt])!==void 0&&(this._cache=r==null?void 0:r[Pt],Bn(r==null?void 0:r[Pt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Or(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Et&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Hn()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Rt&&!e.has("User-Agent")&&(e.set("User-Agent",Rt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Un(this._url,this._timeoutDuration,this._options).then(r=>{this._local=Or(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Kn(s,e){const r=new Fn(s,e),t=async(n,o)=>r.getKey(n,o);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Gn=Te;function qn(s){if(typeof s!="string")throw new ge("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new ge("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ge("Invalid JWT");if(!e)throw new ge("JWTs must contain a payload");let t;try{t=Gn(e)}catch{throw new ge("Failed to base64url decode the payload")}let n;try{n=JSON.parse(qe.decode(t))}catch{throw new ge("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new ge("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ot(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function J(s,e,r=""){const t=Ot(s),n=s==null?void 0:s.length,o=e!==void 0;if(!t||o&&n!==e){const i=r&&`"${r}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return s}function Cr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function He(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function kr(s,e){J(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Jn(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Be(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ct(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const Vn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function zn(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Yn(s){for(let e=0;e<s.length;e++)s[e]=zn(s[e]);return s}const Nr=Vn?s=>s:Yn,Lr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ve(s){if(J(s),Lr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=jn[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function Dr(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function it(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Lr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){const i=Dr(s.charCodeAt(o)),a=Dr(s.charCodeAt(o+1));if(i===void 0||a===void 0){const c=s[o]+s[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function Re(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];J(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const o=s[t];r.set(o,n),n+=o.length}return r}function Mr(s,e={}){const r=(n,o)=>s(o).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function $r(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Xn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Zn(s,e,r){return s&e^~s&r}function Qn(s,e,r){return s&e^s&r^e&r}class eo{constructor(e,r,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=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ct(this.buffer)}update(e){He(this),J(e);const{view:r,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=Ct(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(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){He(this),kr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;r[i++]=128,Be(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let h=i;h<n;h++)r[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=Ct(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Pe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),at=BigInt(2**32-1),Wr=BigInt(32);function to(s,e=!1){return e?{h:Number(s&at),l:Number(s>>Wr&at)}:{h:Number(s>>Wr&at)|0,l:Number(s&at)|0}}function ro(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){const{h:i,l:a}=to(s[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const so=(s,e,r)=>s<<r|e>>>32-r,no=(s,e,r)=>e<<r|s>>>32-r,oo=(s,e,r)=>e<<r-32|s>>>64-r,io=(s,e,r)=>s<<r-32|e>>>64-r,ao=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oe=new Uint32Array(64);class co extends eo{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,r,t,n,o,i,a,c]}set(e,r,t,n,o,i,a,c){this.A=e|0,this.B=r|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,r){for(let h=0;h<16;h++,r+=4)Oe[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const _=Oe[h-15],p=Oe[h-2],w=me(_,7)^me(_,18)^_>>>3,b=me(p,17)^me(p,19)^p>>>10;Oe[h]=b+Oe[h-7]+w+Oe[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const _=me(a,6)^me(a,11)^me(a,25),p=u+_+Zn(a,c,l)+ao[h]+Oe[h]|0,b=(me(t,2)^me(t,13)^me(t,22))+Qn(t,n,o)|0;u=l,l=c,c=a,a=i+p|0,i=o,o=n,n=t,t=p+b|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,o,i,a,c,l,u)}roundClean(){Be(Oe)}destroy(){this.set(0,0,0,0,0,0,0,0),Be(this.buffer)}}class lo extends co{constructor(){super(32);E(this,"A",Pe[0]|0);E(this,"B",Pe[1]|0);E(this,"C",Pe[2]|0);E(this,"D",Pe[3]|0);E(this,"E",Pe[4]|0);E(this,"F",Pe[5]|0);E(this,"G",Pe[6]|0);E(this,"H",Pe[7]|0)}}const uo=Mr(()=>new lo,Xn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kt=BigInt(0),Nt=BigInt(1);function ct(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Ur(s){if(typeof s=="bigint"){if(!ut(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function lt(s){const e=Ur(s).toString(16);return e.length&1?"0"+e:e}function Hr(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?kt:BigInt("0x"+s)}function dt(s){return Hr(Ve(s))}function Br(s){return Hr(Ve(ho(J(s)).reverse()))}function Lt(s,e){ve(e),s=Ur(s);const r=it(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Fr(s,e){return Lt(s,e).reverse()}function ho(s){return Uint8Array.from(s)}const ut=s=>typeof s=="bigint"&&kt<=s;function fo(s,e,r){return ut(s)&&ut(e)&&ut(r)&&e<=s&&s<r}function po(s,e,r,t){if(!fo(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function _o(s){let e;for(e=0;s>kt;s>>=Nt,e+=1);return e}const Dt=s=>(Nt<<BigInt(s))-Nt;function go(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const h=()=>{c.fill(1),l.fill(0),u=0},_=(...y)=>r(l,Re(c,...y)),p=(y=n)=>{l=_(o,y),c=_(),y.length!==0&&(l=_(i,y),c=_())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const A=[];for(;y<e;){c=_();const N=c.slice();A.push(N),y+=c.length}return Re(...A)};return(y,A)=>{h(),p(y);let N;for(;!(N=A(w()));)p();return h(),N}}function Mt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(o,i,a){const c=s[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(r,!0)}function Kr(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const o=s(r,...t);return e.set(r,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ie=BigInt(0),te=BigInt(1),Ne=BigInt(2),Gr=BigInt(3),qr=BigInt(4),Jr=BigInt(5),xo=BigInt(7),Vr=BigInt(8),mo=BigInt(9),zr=BigInt(16);function fe(s,e){const r=s%e;return r>=ie?r:e+r}function de(s,e,r){let t=s;for(;e-- >ie;)t*=t,t%=r;return t}function Yr(s,e){if(s===ie)throw new Error("invert: expected non-zero number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let r=fe(s,e),t=e,n=ie,o=te;for(;r!==ie;){const a=t/r,c=t%r,l=n-o*a;t=r,r=c,n=o,o=l}if(t!==te)throw new Error("invert: does not exist");return fe(n,e)}function $t(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function jr(s,e){const r=(s.ORDER+te)/qr,t=s.pow(e,r);return $t(s,t,e),t}function wo(s,e){const r=(s.ORDER-Jr)/Vr,t=s.mul(e,Ne),n=s.pow(t,r),o=s.mul(e,n),i=s.mul(s.mul(o,Ne),n),a=s.mul(o,s.sub(i,s.ONE));return $t(s,a,e),a}function yo(s){const e=ht(s),r=Xr(s),t=r(e,e.neg(e.ONE)),n=r(e,t),o=r(e,e.neg(t)),i=(s+xo)/zr;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const h=a.mul(l,n),_=a.mul(l,o),p=a.eql(a.sqr(u),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(_,h,w);const b=a.eql(a.sqr(u),c),y=a.cmov(l,u,b);return $t(a,y,c),y}}function Xr(s){if(s<Gr)throw new Error("sqrt is not defined for small field");let e=s-te,r=0;for(;e%Ne===ie;)e/=Ne,r++;let t=Ne;const n=ht(s);for(;Qr(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return jr;let o=n.pow(t,e);const i=(e+te)/Ne;return function(c,l){if(c.is0(l))return l;if(Qr(c,l)!==1)throw new Error("Cannot find square root");let u=r,h=c.mul(c.ONE,o),_=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let w=1,b=c.sqr(_);for(;!c.eql(b,c.ONE);)if(w++,b=c.sqr(b),w===u)throw new Error("Cannot find square root");const y=te<<BigInt(u-w-1),A=c.pow(h,y);u=w,h=c.sqr(A),_=c.mul(_,h),p=c.mul(p,A)}return p}}function bo(s){return s%qr===Gr?jr:s%Vr===Jr?wo:s%zr===mo?yo(s):Xr(s)}const So=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vo(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=So.reduce((t,n)=>(t[n]="function",t),e);return Mt(s,r),s}function Eo(s,e,r){if(r<ie)throw new Error("invalid exponent, negatives unsupported");if(r===ie)return s.ONE;if(r===te)return e;let t=s.ONE,n=e;for(;r>ie;)r&te&&(t=s.mul(t,n)),n=s.sqr(n),r>>=te;return t}function Zr(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((i,a,c)=>s.is0(a)?i:(t[c]=i,s.mul(i,a)),s.ONE),o=s.inv(n);return e.reduceRight((i,a,c)=>s.is0(a)?i:(t[c]=s.mul(i,t[c]),s.mul(i,a)),o),t}function Qr(s,e){const r=(s.ORDER-te)/Ne,t=s.pow(e,r),n=s.eql(t,s.ONE),o=s.eql(t,s.ZERO),i=s.eql(t,s.neg(s.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function Io(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Ao{constructor(e,r={}){E(this,"ORDER");E(this,"BITS");E(this,"BYTES");E(this,"isLE");E(this,"ZERO",ie);E(this,"ONE",te);E(this,"_lengths");E(this,"_sqrt");E(this,"_mod");var i;if(e<=ie)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(i=r.allowedLengths)==null?void 0:i.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:o}=Io(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 fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ie<=e&&e<this.ORDER}is0(e){return e===ie}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return fe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return fe(e*e,this.ORDER)}add(e,r){return fe(e+r,this.ORDER)}sub(e,r){return fe(e-r,this.ORDER)}mul(e,r){return fe(e*r,this.ORDER)}pow(e,r){return Eo(this,e,r)}div(e,r){return fe(e*Yr(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Yr(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=bo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Fr(e,this.BYTES):Lt(e,this.BYTES)}fromBytes(e,r=!1){J(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?Br(e):dt(e);if(a&&(c=fe(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Zr(this,e)}cmov(e,r,t){return t?r:e}}function ht(s,e={}){return new Ao(s,e)}function es(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function ts(s){const e=es(s);return e+Math.ceil(e/2)}function To(s,e,r=!1){J(s);const t=s.length,n=es(e),o=ts(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=r?Br(s):dt(s),a=fe(i,e-te)+te;return r?Fr(a,n):Lt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Fe=BigInt(0),Le=BigInt(1);function ft(s,e){const r=e.negate();return s?r:e}function rs(s,e){const r=Zr(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function ss(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Wt(s,e){ss(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,o=Dt(s),i=BigInt(s);return{windows:r,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function ns(s,e,r){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=r;let a=Number(s&n),c=s>>i;a>t&&(a-=o,c+=Le);const l=e*t,u=l+Math.abs(a)-1,h=a===0,_=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:_,isNegF:p,offsetF:l}}const Ut=new WeakMap,os=new WeakMap;function Ht(s){return os.get(s)||1}function is(s){if(s!==Fe)throw new Error("invalid wNAF")}class Ro{constructor(e,r){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=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Fe;)r&Le&&(t=t.add(n)),n=n.double(),r>>=Le;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Wt(r,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,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Wt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:_,offsetF:p}=ns(t,a,i);t=c,u?o=o.add(ft(_,r[p])):n=n.add(ft(h,r[l]))}return is(t),{p:n,f:o}}wNAFUnsafe(e,r,t,n=this.ZERO){const o=Wt(e,this.bits);for(let i=0;i<o.windows&&t!==Fe;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=ns(t,i,o);if(t=a,!l){const h=r[c];n=n.add(u?h.negate():h)}}return is(t),n}getPrecomputes(e,r,t){let n=Ut.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Ut.set(r,n))),n}cached(e,r,t){const n=Ht(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const o=Ht(e);return o===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),r,n)}createCache(e,r){ss(r,this.bits),os.set(e,r),Ut.delete(e)}hasCache(e){return Ht(e)!==1}}function Po(s,e,r,t){let n=e,o=s.ZERO,i=s.ZERO;for(;r>Fe||t>Fe;)r&Le&&(o=o.add(n)),t&Le&&(i=i.add(n)),n=n.double(),r>>=Le,t>>=Le;return{p1:o,p2:i}}function as(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vo(e),e}else return ht(s,{isLE:r})}function Oo(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Fe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=as(e.p,r.Fp,t),o=as(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function Co(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class cs{constructor(e,r){E(this,"oHash");E(this,"iHash");E(this,"blockLen");E(this,"outputLen");E(this,"finished",!1);E(this,"destroyed",!1);if(Cr(e),J(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let 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),Be(n)}update(e){return He(this),this.iHash.update(e),this}digestInto(e){He(this),J(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ls=(s,e,r)=>new cs(s,e).update(r).digest();ls.create=(s,e)=>new cs(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ds=(s,e)=>(s+(s>=0?e:-e)/us)/e;function ko(s,e,r){const[[t,n],[o,i]]=e,a=ds(i*s,r),c=ds(-n*s,r);let l=s-a*t-c*o,u=-a*n-c*i;const h=l<Ie,_=u<Ie;h&&(l=-l),_&&(u=-u);const p=Dt(Math.ceil(_o(r)/2))+Ke;if(l<Ie||l>=p||u<Ie||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:l,k2neg:_,k2:u}}function Bt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Ft(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return ct(r.lowS,"lowS"),ct(r.prehash,"prehash"),r.format!==void 0&&Bt(r.format),r}class No extends Error{constructor(e=""){super(e)}}const Ce={Err:No,_tlv:{encode:(s,e)=>{const{Err:r}=Ce;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=lt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const o=t>127?lt(n.length/2|128):"";return lt(s)+o+n+e},decode(s,e){const{Err:r}=Ce;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)i=i<<8|u;if(t+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(s){const{Err:e}=Ce;if(s<Ie)throw new e("integer: negative integers are not allowed");let r=lt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Ce;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return dt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Ce,n=J(s,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Ce,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),o=t+n;return e.encode(48,o)}},Ie=BigInt(0),Ke=BigInt(1),us=BigInt(2),pt=BigInt(3),Lo=BigInt(4);function Do(s,e={}){const r=Oo("weierstrass",s,e),{Fp:t,Fn:n}=r;let o=r.CURVE;const{h:i,n:a}=o;Mt(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=fs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(I,g,x){const{x:S,y:P}=g.toAffine(),D=t.toBytes(S);if(ct(x,"isCompressed"),x){u();const k=!t.isOdd(P);return Re(hs(k),D)}else return Re(Uint8Array.of(4),D,t.toBytes(P))}function _(I){J(I,void 0,"Point");const{publicKey:g,publicKeyUncompressed:x}=l,S=I.length,P=I[0],D=I.subarray(1);if(S===g&&(P===2||P===3)){const k=t.fromBytes(D);if(!t.isValid(k))throw new Error("bad point: is not on curve, wrong x");const M=b(k);let R;try{R=t.sqrt(M)}catch(X){const q=X instanceof Error?": "+X.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}u();const $=t.isOdd(R);return(P&1)===1!==$&&(R=t.neg(R)),{x:k,y:R}}else if(S===x&&P===4){const k=t.BYTES,M=t.fromBytes(D.subarray(0,k)),R=t.fromBytes(D.subarray(k,k*2));if(!y(M,R))throw new Error("bad point: is not on curve");return{x:M,y:R}}else throw new Error(`bad point: got length ${S}, expected compressed=${g} or uncompressed=${x}`)}const p=e.toBytes||h,w=e.fromBytes||_;function b(I){const g=t.sqr(I),x=t.mul(g,I);return t.add(t.add(x,t.mul(I,o.a)),o.b)}function y(I,g){const x=t.sqr(g),S=b(I);return t.eql(x,S)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const A=t.mul(t.pow(o.a,pt),Lo),N=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(A,N)))throw new Error("bad curve params: a or b");function K(I,g,x=!1){if(!t.isValid(g)||x&&t.is0(g))throw new Error(`bad point coordinate ${I}`);return g}function W(I){if(!(I instanceof L))throw new Error("Weierstrass Point expected")}function Y(I){if(!c||!c.basises)throw new Error("no endo");return ko(I,c.basises,n.ORDER)}const G=Kr((I,g)=>{const{X:x,Y:S,Z:P}=I;if(t.eql(P,t.ONE))return{x,y:S};const D=I.is0();g==null&&(g=D?t.ONE:t.inv(P));const k=t.mul(x,g),M=t.mul(S,g),R=t.mul(P,g);if(D)return{x:t.ZERO,y:t.ZERO};if(!t.eql(R,t.ONE))throw new Error("invZ was invalid");return{x:k,y:M}}),O=Kr(I=>{if(I.is0()){if(e.allowInfinityPoint&&!t.is0(I.Y))return;throw new Error("bad point: ZERO")}const{x:g,y:x}=I.toAffine();if(!t.isValid(g)||!t.isValid(x))throw new Error("bad point: x or y not field elements");if(!y(g,x))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(I,g,x,S,P){return x=new L(t.mul(x.X,I),x.Y,x.Z),g=ft(S,g),x=ft(P,x),g.add(x)}const T=class T{constructor(g,x,S){E(this,"X");E(this,"Y");E(this,"Z");this.X=K("x",g),this.Y=K("y",x,!0),this.Z=K("z",S),Object.freeze(this)}static CURVE(){return o}static fromAffine(g){const{x,y:S}=g||{};if(!g||!t.isValid(x)||!t.isValid(S))throw new Error("invalid affine point");if(g instanceof T)throw new Error("projective point not allowed");return t.is0(x)&&t.is0(S)?T.ZERO:new T(x,S,t.ONE)}static fromBytes(g){const x=T.fromAffine(w(J(g,void 0,"point")));return x.assertValidity(),x}static fromHex(g){return T.fromBytes(it(g))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(g=8,x=!0){return C.createCache(this,g),x||this.multiply(pt),this}assertValidity(){O(this)}hasEvenY(){const{y:g}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(g)}equals(g){W(g);const{X:x,Y:S,Z:P}=this,{X:D,Y:k,Z:M}=g,R=t.eql(t.mul(x,M),t.mul(D,P)),$=t.eql(t.mul(S,M),t.mul(k,P));return R&&$}negate(){return new T(this.X,t.neg(this.Y),this.Z)}double(){const{a:g,b:x}=o,S=t.mul(x,pt),{X:P,Y:D,Z:k}=this;let M=t.ZERO,R=t.ZERO,$=t.ZERO,B=t.mul(P,P),X=t.mul(D,D),q=t.mul(k,k),H=t.mul(P,D);return H=t.add(H,H),$=t.mul(P,k),$=t.add($,$),M=t.mul(g,$),R=t.mul(S,q),R=t.add(M,R),M=t.sub(X,R),R=t.add(X,R),R=t.mul(M,R),M=t.mul(H,M),$=t.mul(S,$),q=t.mul(g,q),H=t.sub(B,q),H=t.mul(g,H),H=t.add(H,$),$=t.add(B,B),B=t.add($,B),B=t.add(B,q),B=t.mul(B,H),R=t.add(R,B),q=t.mul(D,k),q=t.add(q,q),B=t.mul(q,H),M=t.sub(M,B),$=t.mul(q,X),$=t.add($,$),$=t.add($,$),new T(M,R,$)}add(g){W(g);const{X:x,Y:S,Z:P}=this,{X:D,Y:k,Z:M}=g;let R=t.ZERO,$=t.ZERO,B=t.ZERO;const X=o.a,q=t.mul(o.b,pt);let H=t.mul(x,D),ee=t.mul(S,k),ne=t.mul(P,M),le=t.add(x,S),V=t.add(D,k);le=t.mul(le,V),V=t.add(H,ee),le=t.sub(le,V),V=t.add(x,P);let oe=t.add(D,M);return V=t.mul(V,oe),oe=t.add(H,ne),V=t.sub(V,oe),oe=t.add(S,P),R=t.add(k,M),oe=t.mul(oe,R),R=t.add(ee,ne),oe=t.sub(oe,R),B=t.mul(X,V),R=t.mul(q,ne),B=t.add(R,B),R=t.sub(ee,B),B=t.add(ee,B),$=t.mul(R,B),ee=t.add(H,H),ee=t.add(ee,H),ne=t.mul(X,ne),V=t.mul(q,V),ee=t.add(ee,ne),ne=t.sub(H,ne),ne=t.mul(X,ne),V=t.add(V,ne),H=t.mul(ee,V),$=t.add($,H),H=t.mul(oe,V),R=t.mul(le,R),R=t.sub(R,H),H=t.mul(le,ee),B=t.mul(oe,B),B=t.add(B,H),new T(R,$,B)}subtract(g){return this.add(g.negate())}is0(){return this.equals(T.ZERO)}multiply(g){const{endo:x}=e;if(!n.isValidNot0(g))throw new Error("invalid scalar: out of range");let S,P;const D=k=>C.cached(this,k,M=>rs(T,M));if(x){const{k1neg:k,k1:M,k2neg:R,k2:$}=Y(g),{p:B,f:X}=D(M),{p:q,f:H}=D($);P=X.add(H),S=v(x.beta,B,q,k,R)}else{const{p:k,f:M}=D(g);S=k,P=M}return rs(T,[S,P])[0]}multiplyUnsafe(g){const{endo:x}=e,S=this;if(!n.isValid(g))throw new Error("invalid scalar: out of range");if(g===Ie||S.is0())return T.ZERO;if(g===Ke)return S;if(C.hasCache(this))return this.multiply(g);if(x){const{k1neg:P,k1:D,k2neg:k,k2:M}=Y(g),{p1:R,p2:$}=Po(T,S,D,M);return v(x.beta,R,$,P,k)}else return C.unsafe(S,g)}toAffine(g){return G(this,g)}isTorsionFree(){const{isTorsionFree:g}=e;return i===Ke?!0:g?g(T,this):C.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:g}=e;return i===Ke?this:g?g(T,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(g=!0){return ct(g,"isCompressed"),this.assertValidity(),p(T,this,g)}toHex(g=!0){return Ve(this.toBytes(g))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};E(T,"BASE",new T(o.Gx,o.Gy,t.ONE)),E(T,"ZERO",new T(t.ZERO,t.ONE,t.ZERO)),E(T,"Fp",t),E(T,"Fn",n);let L=T;const F=n.BITS,C=new Ro(L,e.endo?Math.ceil(F/2):F);return L.BASE.precompute(8),L}function hs(s){return Uint8Array.of(s?2:3)}function fs(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Mo(s,e={}){const{Fn:r}=s,t=e.randomBytes||$r,n=Object.assign(fs(s.Fp,r),{seed:ts(r.ORDER)});function o(p){try{const w=r.fromBytes(p);return r.isValidNot0(w)}catch{return!1}}function i(p,w){const{publicKey:b,publicKeyUncompressed:y}=n;try{const A=p.length;return w===!0&&A!==b||w===!1&&A!==y?!1:!!s.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return To(J(p,n.seed,"seed"),r.ORDER)}function c(p,w=!0){return s.BASE.multiply(r.fromBytes(p)).toBytes(w)}function l(p){const{secretKey:w,publicKey:b,publicKeyUncompressed:y}=n;if(!Ot(p)||"_lengths"in r&&r._lengths||w===b)return;const A=J(p,void 0,"key").length;return A===b||A===y}function u(p,w,b=!0){if(l(p)===!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=r.fromBytes(p);return s.fromBytes(w).multiply(y).toBytes(b)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},_=Co(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:s,utils:h,lengths:n})}function $o(s,e,r={}){Cr(e),Mt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||$r,n=r.hmac||((g,x)=>ls(e,g,x)),{Fp:o,Fn:i}=s,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:p}=Mo(s,r),w={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},b=a*us<o.ORDER;function y(g){const x=a>>Ke;return g>x}function A(g,x){if(!i.isValidNot0(x))throw new Error(`invalid signature ${g}: out of range 1..Point.Fn.ORDER`);return x}function N(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function K(g,x){Bt(x);const S=p.signature,P=x==="compact"?S:x==="recovered"?S+1:void 0;return J(g,P)}class W{constructor(x,S,P){E(this,"r");E(this,"s");E(this,"recovery");if(this.r=A("r",x),this.s=A("s",S),P!=null){if(N(),![0,1,2,3].includes(P))throw new Error("invalid recovery id");this.recovery=P}Object.freeze(this)}static fromBytes(x,S=w.format){K(x,S);let P;if(S==="der"){const{r:R,s:$}=Ce.toSig(J(x));return new W(R,$)}S==="recovered"&&(P=x[0],S="compact",x=x.subarray(1));const D=p.signature/2,k=x.subarray(0,D),M=x.subarray(D,D*2);return new W(i.fromBytes(k),i.fromBytes(M),P)}static fromHex(x,S){return this.fromBytes(it(x),S)}assertRecovery(){const{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new W(this.r,this.s,x)}recoverPublicKey(x){const{r:S,s:P}=this,D=this.assertRecovery(),k=D===2||D===3?S+a:S;if(!o.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(k),R=s.fromBytes(Re(hs((D&1)===0),M)),$=i.inv(k),B=G(J(x,void 0,"msgHash")),X=i.create(-B*$),q=i.create(P*$),H=s.BASE.multiplyUnsafe(X).add(R.multiplyUnsafe(q));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(x=w.format){if(Bt(x),x==="der")return it(Ce.hexFromSig(this));const{r:S,s:P}=this,D=i.toBytes(S),k=i.toBytes(P);return x==="recovered"?(N(),Re(Uint8Array.of(this.assertRecovery()),D,k)):Re(D,k)}toHex(x){return Ve(this.toBytes(x))}}const Y=r.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");const S=dt(x),P=x.length*8-c;return P>0?S>>BigInt(P):S},G=r.bits2int_modN||function(x){return i.create(Y(x))},O=Dt(c);function v(g){return po("num < 2^"+c,g,Ie,O),i.toBytes(g)}function L(g,x){return J(g,void 0,"message"),x?J(e(g),void 0,"prehashed message"):g}function F(g,x,S){const{lowS:P,prehash:D,extraEntropy:k}=Ft(S,w);g=L(g,D);const M=G(g),R=i.fromBytes(x);if(!i.isValidNot0(R))throw new Error("invalid private key");const $=[v(R),v(M)];if(k!=null&&k!==!1){const H=k===!0?t(p.secretKey):k;$.push(J(H,void 0,"extraEntropy"))}const B=Re(...$),X=M;function q(H){const ee=Y(H);if(!i.isValidNot0(ee))return;const ne=i.inv(ee),le=s.BASE.multiply(ee).toAffine(),V=i.create(le.x);if(V===Ie)return;const oe=i.create(ne*i.create(X+V*R));if(oe===Ie)return;let ks=(le.x===V?0:2)|Number(le.y&Ke),Ns=oe;return P&&y(oe)&&(Ns=i.neg(oe),ks^=1),new W(V,Ns,b?void 0:ks)}return{seed:B,k2sig:q}}function C(g,x,S={}){const{seed:P,k2sig:D}=F(g,x,S);return go(e.outputLen,i.BYTES,n)(P,D).toBytes(S.format)}function T(g,x,S,P={}){const{lowS:D,prehash:k,format:M}=Ft(P,w);if(S=J(S,void 0,"publicKey"),x=L(x,k),!Ot(g)){const R=g instanceof W?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+R)}K(g,M);try{const R=W.fromBytes(g,M),$=s.fromBytes(S);if(D&&R.hasHighS())return!1;const{r:B,s:X}=R,q=G(x),H=i.inv(X),ee=i.create(q*H),ne=i.create(B*H),le=s.BASE.multiplyUnsafe(ee).add($.multiplyUnsafe(ne));return le.is0()?!1:i.create(le.x)===B}catch{return!1}}function I(g,x,S={}){const{prehash:P}=Ft(S,w);return x=L(x,P),W.fromBytes(g,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:p,Point:s,sign:C,verify:T,recoverPublicKey:I,Signature:W,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Wo={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ps=BigInt(2);function Uo(s){const e=Kt.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,h=de(u,r,e)*u%e,_=de(h,r,e)*u%e,p=de(_,ps,e)*l%e,w=de(p,n,e)*p%e,b=de(w,o,e)*w%e,y=de(b,a,e)*b%e,A=de(y,c,e)*y%e,N=de(A,a,e)*b%e,K=de(N,r,e)*u%e,W=de(K,i,e)*w%e,Y=de(W,t,e)*l%e,G=de(Y,ps,e);if(!Gt.eql(Gt.sqr(G),s))throw new Error("Cannot find square root");return G}const Gt=ht(Kt.p,{sqrt:Uo}),Ho=$o(Do(Kt,{Fp:Gt,endo:Wo}),uo),Bo=BigInt(0),ze=BigInt(1),Fo=BigInt(2),Ko=BigInt(7),Go=BigInt(256),qo=BigInt(113),_s=[],gs=[],xs=[];for(let s=0,e=ze,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],_s.push(2*(5*t+r)),gs.push((s+1)*(s+2)/2%64);let n=Bo;for(let o=0;o<7;o++)e=(e<<ze^(e>>Ko)*qo)%Go,e&Fo&&(n^=ze<<(ze<<BigInt(o))-ze);xs.push(n)}const ms=ro(xs,!0),Jo=ms[0],Vo=ms[1],ws=(s,e,r)=>r>32?oo(s,e,r):so(s,e,r),ys=(s,e,r)=>r>32?io(s,e,r):no(s,e,r);function zo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)r[i]=s[i]^s[i+10]^s[i+20]^s[i+30]^s[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=r[c],u=r[c+1],h=ws(l,u,1)^r[a],_=ys(l,u,1)^r[a+1];for(let p=0;p<50;p+=10)s[i+p]^=h,s[i+p+1]^=_}let n=s[2],o=s[3];for(let i=0;i<24;i++){const a=gs[i],c=ws(n,o,a),l=ys(n,o,a),u=_s[i];n=s[u],o=s[u+1],s[u]=c,s[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=s[i+a];for(let a=0;a<10;a++)s[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Jo[t],s[1]^=Vo[t]}Be(r)}class qt{constructor(e,r,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=r,this.outputLen=t,this.enableXOF=n,this.rounds=o,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Jn(this.state)}clone(){return this._cloneInto()}keccak(){Nr(this.state32),zo(this.state32,this.rounds),Nr(this.state32),this.posOut=0,this.pos=0}update(e){He(this),J(e);const{blockLen:r,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(r-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){He(this,!1),J(e),this.finish();const r=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(r.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 ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(kr(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,Be(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new qt(r,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 bs=((s,e,r,t={})=>Mr(()=>new qt(e,s,r),t))(1,136,32),Yo=60;class jo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Kn(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Yo<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:o}=await Ln(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return qn(e)}recoverPersonalSignSigner(e,r){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=bs(o),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Xo(a),l=c.slice(0,32),u=c.slice(32,64),h=c[64],_=h>=27?h-27:h,b=new Ho.Signature(Ss(l),Ss(u)).addRecoveryBit(_).recoverPublicKey(i).toBytes(!1).slice(1),y=bs(b);return"0x"+Ve(y.slice(12))}}function Xo(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Ss(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Zo=3e4,Qo=1e3;class ei{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,Qo*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Zo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const ti=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class De{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=De.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const i=await De.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((r,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=De.generateRandom16Hex(),l=De.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const _=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),W(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,b=30;let y=0,A=null;const N=()=>{clearInterval(K),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+b+"초간 대기합니다"),A=setTimeout(()=>{W(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},b*1e3)},K=setInterval(()=>{y++;try{_.closed&&(y<=w?N():(W(),t(new Error("로그인이 취소되었습니다"))))}catch{N()}},1e3),W=()=>{clearTimeout(p),clearInterval(K),A&&clearTimeout(A),window.removeEventListener("message",Y)},Y=G=>{if(G.origin!==e.expectedOrigin)return;if(!ti.has(G.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",G.origin),W(),t(new Error("Unauthorized OAuth origin"));return}W();const O=typeof G.data.status=="string",v=O?G.data.data??{}:G.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:O?"wrapped":"flat",status:O?G.data.status:"(flat)"});const L=(v==null?void 0:v.state)??G.data.state;if(!L||L!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(O&&G.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",v==null?void 0:v.error),t(new Error((v==null?void 0:v.error)||"Authentication failed"));return}if(!O&&(v!=null&&v.error)){d.error("[CROSSx] OAuth 실패:",v.error),t(new Error(v.error||"Authentication failed"));return}const F=v==null?void 0:v.idToken,C=v==null?void 0:v.accessToken,T=C??F;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!C,hasIdToken:!!F}),!T){d.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const I=g=>{De.verifyIdTokenNonce(g,l).then(()=>r(T)).catch(x=>{d.error("[CROSSx] nonce 검증 실패:",x),t(x instanceof Error?x:new Error("nonce verification failed"))})};C?C.split(".").length===3?I(C):F?I(F):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(T)):F?I(F):t(new Error("Token not found in response"))};window.addEventListener("message",Y)})}}const Ye="crossx_wallet_data",Ge="crossx_mock_pin_hash";class ri{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(Ye)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(Ye);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(Ye,n);const o=(r=this.pinStore)==null?void 0:r.get();return o&&(await this.storage.set(Ge,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new m(f.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(Ye);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,o,i){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${o} from=${i}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,o){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ge);return r&&r!==e?!1:(r||await this.storage.set(Ge,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new m(f.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Ge);if(n&&t&&n!==t)throw new m(f.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ge,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new m(f.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(f.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Ye,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Ge,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class je{constructor(e,r,t,n,o){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(js))return e;if(this._onTokenRefresh&&await this.deduplicatedRefresh()){const t=this.tokenStore.get();if(t)return t}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new m(f.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u;const o=await this.ensureValidToken(),i=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:i,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const p=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:p,url:i,method:e});const w=je.mapGatewayError(_.code,_.data);if(w===f.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh&&(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh()))return this.request(e,r,t,!0);const b=je.getGatewayErrorMessage(_.code,p),y=_.data,A=w===f.PIN_LOCKED?je.extractLockDetails(y):y??void 0,N=new m(w,b,A);throw w===f.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(d.warn("[CROSSx] Gateway -10002 갱신 재시도 실패 — 강제 로그아웃 실행"),this._onUnauthorized()),N}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:i,method:e}),_.data??_}return _}catch(h){if(h instanceof m)throw h;const _=((c=h.response)==null?void 0:c.status)??h.status;if((_===401||_===403)&&!n&&this._onTokenRefresh&&(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh()))return this.request(e,r,t,!0);if((l=h.response)!=null&&l.data){const p=h.response.data,w=p.message||p.data||"API 요청에 실패했습니다",b=p.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:b,message:w,url:i,method:e,status:(u=h.response)==null?void 0:u.status}),new m(f.UNKNOWN_ERROR,`Wallet Gateway 오류 (${b}): ${w}`)}throw h}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new m(f.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new m(f.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new m(f.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new m(f.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.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,r,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:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,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(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,i);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,o)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e};return(await this.request("POST","/mnemonic/verify-password",r)).valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new m(f.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??e,t=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);return t?{lockExpiresAt:t>1e10?t:t*1e3}:{}}static mapGatewayError(e,r){switch(e){case-10002:return f.AUTH_NOT_AUTHENTICATED;case-10001:return f.UNKNOWN_ERROR;case-10006:return f.GATEWAY_INTERNAL_ERROR;case-10007:return f.BROADCAST_FAILED;case-10008:return f.GATEWAY_LOCK_CONFLICT;case-10004:return f.WALLET_ALREADY_EXISTS;case-10005:return f.WALLET_NOT_FOUND;case-10011:return f.WALLET_NOT_FOUND;case-10030:return f.WALLET_INCONSISTENT_STATE;case-10010:return f.MIGRATION_FAILED;case-10012:return f.MIGRATION_BACKUP_EXISTS;case-10013:return f.WITHDRAW_FAILED;case-10027:return f.MIGRATION_PIN_LOCKED;case-10022:return f.PROJECT_NOT_REGISTERED;case-10023:return f.PROJECT_ID_MISSING;case-10024:return f.ORIGIN_NOT_ALLOWED;case-10025:return f.INVALID_APP_TYPE;case-10028:return f.PIN_WRONG;case-10029:return f.PIN_INVALID;case-10031:return f.PIN_LOCKED;case-10032:return f.PIN_REPEATED_PATTERN;case-10026:return f.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return f.PREPARE_FAILED;case-10016:return f.PREPARE_EXPIRED;case-10017:case-10018:return f.PREPARE_MISMATCH;case-10020:return f.CHAIN_NOT_SUPPORTED;case-10021:return f.INVALID_CHAIN;case-10040:return f.HMAC_REQUIRED;case-10041:return f.HMAC_VERIFICATION_FAILED;default:return f.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class Xe{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}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 r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=Xe.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?Zs:Xs;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new m(Xe.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=Xe.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new m(f.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Ze).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return f.CHAIN_NOT_SUPPORTED;case-10021:return f.INVALID_CHAIN;case-10022:return f.PROJECT_NOT_REGISTERED;case-10023:return f.PROJECT_ID_MISSING;case-10024:return f.APP_IDENTIFIER_MISSING;case-10025:return f.INVALID_APP_TYPE;default:return f.UNKNOWN_ERROR}}}const vs="__crossx-confirm-style",re="__crossx-confirm-overlay",si={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 Es(s,e){const r=si[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const ni=`
|
|
1
|
+
var CROSSx=function(X){"use strict";var Go=Object.defineProperty;var qo=(X,f,g)=>f in X?Go(X,f,{enumerable:!0,configurable:!0,writable:!0,value:g}):X[f]=g;var T=(X,f,g)=>qo(X,typeof f!="symbol"?f+"":f,g);var xt,Ns;var f=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(f||{});class g extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,g.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Qe={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Ms=Object.fromEntries(Object.entries(Qe).map(([s,e])=>[s,e.caipId])),$s=new Map(Object.values(Qe).map(s=>[s.caipId,s]));new Map(Object.values(Qe).map(s=>[s.chainId,s]));const Ws={symbol:"",decimals:18};function mt(s){var e;return((e=$s.get(s))==null?void 0:e.nativeCurrency)??Ws}class Zt{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new g(f.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new g(f.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let be=null;function Jo(s){}function Qt(s){be=s}const d={info(...s){if(be){be.log(...s);return}console.log(...s)},log(...s){if(be){be.log(...s);return}},warn(...s){if(be){be.warn(...s);return}},error(...s){if(be){be.error(...s);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로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",pinLocked_failureWarning:"PIN이 올바르지 않습니다. 추가 실패 시 계정이 잠금됩니다.",pinLocked_permanent:"너무 많은 시도 실패로 계정이 영구 잠금되었습니다.",alert_sessionExpired:"인증이 만료되었습니다. 확인을 누른 뒤 다시 로그인해 주세요.",alert_accountWithdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 확인 후 다시 로그인해 주세요.",alert_walletNotFound:"지갑 정보를 찾을 수 없습니다. 확인 후 다시 로그인해 주세요.",alert_differentAccount:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
2
|
+
|
|
3
|
+
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.
|
|
4
|
+
|
|
5
|
+
[확인] 이전과 같은 계정으로 다시 로그인 시도
|
|
6
|
+
[취소] 로그아웃하고 닫기`},er={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Incorrect PIN. Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Tap OK and sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Tap OK and sign in again.",alert_walletNotFound:"Wallet data could not be found. Tap OK and sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
|
|
7
|
+
|
|
8
|
+
For security, you must continue with the same account.
|
|
9
|
+
|
|
10
|
+
OK → Try signing in again with the correct account
|
|
11
|
+
Cancel → Sign out and close`},Hs={ko:Us,en:er};function ke(s="en",e){return Hs[s]??er}const tr="crossx_access_token",rr="crossx_refresh_token",sr="crossx_user_info";class Bs{constructor(e,r,t,n,i,o,a){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,r){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new g(f.AUTH_FAILED,`${r} 실패 (코드 ${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 g(f.AUTH_FAILED,`${r} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){let r;try{const t=e==null?void 0:e.provider;let n="/login";t==="google"?n="/google":t==="apple"&&(n="/apple");const{oauthServiceUrl:i}=this.config,o=`${i}${n}`;d.log(`[CROSSx] OAuth 팝업 열기 (${t||"일반"} 로그인)`),r=await this.oauth.openAuth({authUrl:o,expectedOrigin:new URL(i).origin}),d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")")}catch(t){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",t);const n=t instanceof Error?t.message:"Sign in failed";throw/팝업|popup/i.test(n)?new g(f.OAUTH_POPUP_BLOCKED,n):new g(f.AUTH_FAILED,n)}return this.processFirebaseToken(r)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e){var n,i,o,a;let r,t=!1;try{const{authApiUrl:c}=this.config,{accessToken:l,refreshToken:u}=await this.exchangeFirebaseToken(e,c);let h,_;try{const w=this.crypto.decodeJWT(e);_=(n=w.firebase)==null?void 0:n.sign_in_provider;const E=((i=w.firebase)==null?void 0:i.identities)??{};_==="google.com"?h=(o=E["google.com"])==null?void 0:o[0]:_==="apple.com"&&(h=(a=E["apple.com"])==null?void 0:a[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",_,"hasProviderSub:",!!h)}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(l){const w=this.crypto.decodeJWT(l);d.log("[CROSSx] access_token 디코딩 — sub:",w.sub,"exp:",w.exp);const E=await this.crypto.verifyJWT(l);if(t=E.signatureVerified??!1,!E.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const y=E.payload;r={id:y.sub,email:y.email,signInProvider:_,providerSub:h},this.tokenStore.set(l),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l),u&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u):u&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const w=this.crypto.decodeJWT(e);r={id:w.sub,email:w.email,signInProvider:_,providerSub:h},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",r.id)}d.log("[CROSSx] 사용자 정보 — id:",r.id);const p=this.useCookieAuth?{id:r.id,signInProvider:r.signInProvider,providerSub:r.providerSub}:r;await this.storage.set(this.STORAGE_KEY_USER,p),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,t)}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(f.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){return d.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const l=this.tokenStore.get()??"";l&&(i.access_token=l),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new g(f.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,c);const l=this.extractRefreshToken(a);l&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,l)}return d.log("[CROSSx] silentRefresh 성공"),c}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(sr);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(tr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(rr);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(sr),await this.storage.remove(tr),await this.storage.remove(rr),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof g&&i.code===f.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(i.code===f.PROJECT_NOT_REGISTERED||i.code===f.PROJECT_ID_MISSING||i.code===f.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}}class Fs{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Ks{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new g(f.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class wt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Gs{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new g(f.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class qs{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}var et={environment:"production"};const tt={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(s){const e=s.environment;return e&&e in tt?tt[e]:null}function Vs(){try{if(typeof et<"u"){const s=typeof et=="string"?JSON.parse(et):et,e=Js(s);if(e)return e}}catch{}return tt.production}const zs=2e3,nr=6e4,Ys=1e3,js=1e4,Xs="0x77359400",ir="0x3B9ACA00",or=130,ar=6,cr=18,lr=3e4,Zs=5*60*1e3,Qs=30*1e3,se=class se extends qs{constructor(e,r,t,n,i,o,a,c,l,u,h){var _,p;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&Qt(e.logger),this.confirmation=l,this.pinStore=h??new wt,this.chainRegistry=u,this.jsonRpc=new Gs(u,i),this.signInUseCase=new Bs(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Fs(this.internalConfig,t,c),this.migrateWalletUseCase=new Ks(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v1.3.11 초기화 중..."),this.confirmation.setMessages(ke(this._config.locale));try{const n=Vs();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=await this.signInUseCase.restoreSession();if(i!=null&&i.success){this.applyAuthResult(i);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(o){if(!(o instanceof g&&o.code===f.PIN_CANCELLED))throw o;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.3.11 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??null}catch(n){throw new g(f.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new g(f.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};r={...e,provider:t}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(f.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const r=await this.signIn(e);if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof g&&t.code===f.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new g(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithOAuthToken(e);return r.success&&this.applyAuthResult(r),r}catch(r){throw new g(f.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",r)}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new g(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new g(f.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new g(f.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof g&&r.code===f.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof g?r:new g(f.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.ensurePinForSigning();const n=r.length,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},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 g?e:new g(f.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof g?r:new g(f.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(ke(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const r=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",r);const t=await this.handleMigrationFlow(r);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new g(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const r=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof g&&r.code===f.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new g(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}await this.ensurePinSetup();try{const r=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof g&&r.code===f.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new g(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(f.USER_REJECTED,"User rejected the message signing request");try{const o=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(r,o.signature,n.address),{chainId:e,signature:o.signature,message:r,address:n.address}}catch(o){throw o instanceof g?o:new g(f.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(f.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");se.validateTypedDataChainId(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(f.USER_REJECTED,"User rejected the typed data signing request");try{const o=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return se.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof g?o:new g(f.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,r){return this.signTypedData(se.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=mt(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)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(f.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return se.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof g)throw a;const c=a instanceof Error?a.message:String(a);throw new g(f.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new g(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=mt(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)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(f.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof g)throw a;const c=a instanceof Error?a.message:String(a);throw new g(f.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??Ys,i=js,o=t.timeoutMs??nr,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(f.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var E,y;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??zs,l=i??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??nr,u=mt(e),h=r.from??"";let _,p;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(R=>{_=R;const N=BigInt(R.gasUsed)*BigInt(R.effectiveGasPrice),B=r.value?BigInt(r.value):0n,M=se.formatTxAmount(r.value,u.symbol,u.decimals),V=se.formatTxAmount("0x"+N.toString(16),u.symbol,u.decimals),F=se.formatTxAmount("0x"+(B+N).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:R.from,to:R.to??r.to,amount:M,fees:V,total:F,nativeSymbol:u.symbol,status:R.status==="0x1"?"success":"reverted"}}).catch(R=>(p=R instanceof Error?R:new Error(String(R)),{chainId:e,txHash:a,from:h,to:r.to,amount:se.formatTxAmount(r.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:r.to},w),p)throw p;return{chainId:e,txHash:a,receipt:_}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(f.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(f.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(f.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(f.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(f.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new g(f.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(f.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:se.formatWei(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(f.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const r=BigInt(e);if(r===0n)return"0";const t=10n**BigInt(cr),n=r/t,o=(r%t).toString().padStart(cr,"0").replace(/0+$/,"").slice(0,ar);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Zt(this,e)}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(f.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,r,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const i=10n**BigInt(t),o=n/i,c=(n%i).toString().padStart(t,"0").slice(0,ar).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${r}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const h=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(h===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const _=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,h,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const p=_.pinStatus;if(o=p.maxAttempts,i=o-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const w=p.lockExpiresAt*1e3,E=Math.max(1,Math.round((w-Date.now())/1e3)),y=E<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${E}초, 메시지: ${y}`),await this.confirmation.showRecoveryPinLockedPrompt(E,y),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof g))throw _;if(_.code===f.MIGRATION_PIN_LOCKED){const p=_.details;if(o=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((p==null?void 0:p.lockExpiresAt)??0)*1e3,E=Math.max(1,Math.round((w-Date.now())/1e3)),y=E<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${E}초`),await this.confirmation.showRecoveryPinLockedPrompt(E,y),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const h=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof g&&h.code===f.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}async withResolvedGasAndFee(e,r){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,h,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],r):null,i?this.estimateGas(e,r):null,o?this.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=h,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const p=_;if(p){const w=ir;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(w)).toString(16),c.maxPriorityFeePerGas=w,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Xs,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=ir,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,r){const t=se.extractDomainChainId(r);if(e==="0"){if(t!==void 0&&t!==0)throw new g(f.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const i=Number(n[1]);if(t===void 0)throw new g(f.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new g(f.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const r=e.domain;if(r==null||typeof r!="object")return;const t=r.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new g(f.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(r.length!==or)throw new g(f.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${or} hex 문자(65 바이트) 예상, 현재 ${r.length}`)}static validateSignedTxFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new g(f.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(r.length<2)throw new g(f.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(f.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var r,t,n,i;this.authenticated=e.success,this.userId=((r=e.user)==null?void 0:r.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=se.normalizeLoginType((i=e.user)==null?void 0:i.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}async signInAgain(){var n,i;this.ensureInitialized();const e=this.providerSub,r=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const o=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(o)}catch(h){throw this.clearAuthState(),h}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((i=a.user)==null?void 0:i.id)??null;if(!(e?!!c&&c===e:r?!!l&&r===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const h=ke(this._config.locale??"en");return(typeof globalThis.confirm=="function"?globalThis.confirm(h.alert_differentAccount):!1)?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(r){const t=ke(this._config.locale??"en");if(r instanceof g&&r.code===f.WITHDRAW_FAILED)throw d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),typeof globalThis.alert=="function"&&globalThis.alert(t.alert_accountWithdrawn),this.clearAuthState(),r;if(r instanceof g&&r.code===f.WALLET_NOT_FOUND)throw d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),typeof globalThis.alert=="function"&&globalThis.alert(t.alert_walletNotFound),this.clearAuthState(),r;if(!(r instanceof g)||r.code!==f.SESSION_EXPIRED)throw r;d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),typeof globalThis.alert=="function"&&globalThis.alert(t.alert_sessionExpired);const n=await this.signInAgain();if(!n.success)throw new g(f.SESSION_EXPIRED,n.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new g(f.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const r=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new g(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=ke(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new g(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.pinStore.clear(),u instanceof g){if(u.code===f.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===f.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===f.PIN_LOCKED)return se.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new g(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof g&&(c.code===f.AUTH_NOT_AUTHENTICATED||c.code===f.AUTH_TOKEN_EXPIRED||c.code===f.SESSION_EXPIRED)&&c.code!==f.SESSION_EXPIRED){const{alert_sessionExpired:l}=ke(this._config.locale??"en");typeof globalThis.alert=="function"&&globalThis.alert(l)}throw o(c),c}finally{this._verifyPinMutex=null}}static buildPinLockedResult(e,r){const t=e.details;if(t!=null&&t.permanent)return{ok:!1,error:r.pinLocked_permanent};if((t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts){const n=t.maxAttempts-t.remainingAttempts;return{ok:!1,error:r.pinLocked_failureWarning,attemptCount:n,maxAttempts:t.maxAttempts}}return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}async loadWalletAfterAuth(e){if(!this.userId)return;const r=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",r),r!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const i=e!==void 0?t.find(o=>o.index===e)??t[0]:t[0];this.address=i.address,this.activeWalletIndex=i.index,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:i.address,index:i.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){const r=ke(this._config.locale??"en");let t,n,i,o;const a=c=>{if(c.code===f.PIN_WRONG)return t=r.pinInput_error,n=void 0,i=void 0,o=void 0,!0;if(c.code===f.PIN_INVALID)return t=c.message,n=void 0,i=void 0,o=void 0,!0;if(c.code===f.PIN_LOCKED){const l=c.details;return l!=null&&l.permanent?(t=r.pinLocked_permanent,n=void 0,i=void 0,o=void 0):(l==null?void 0:l.remainingAttempts)!=null&&l.remainingAttempts>0&&l.maxAttempts?(t=r.pinLocked_failureWarning,n=void 0,i=l.maxAttempts-l.remainingAttempts,o=l.maxAttempts):(t="Too many failed attempts. Your account is temporarily locked.",n=l==null?void 0:l.lockExpiresAt,i=void 0,o=void 0),!0}return!1};try{return await e()}catch(c){if(!(c instanceof g&&a(c)))throw c}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t),this.pinStore.clear(),await this.ensureVerifiedPin(t,n,i,o),n=void 0,i=void 0,o=void 0;try{return await e()}catch(c){if(c instanceof g&&a(c))continue;throw c}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new g(f.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 g(f.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new g(f.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Qt(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};se.OFFCHAIN_CHAIN_ID="0";let rt=se;class en{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const yt="crossx-sdk",tn=1,pe="data",Ne="keys",st="aes-primary",rn=12;class dr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,tn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(pe)||i.createObjectStore(pe),i.objectStoreNames.contains(Ne)||i.createObjectStore(Ne)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,st);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,st,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===yt)return null;try{const e=await this.openDB(yt),r=e.transaction([Ne,pe],"readonly"),t=r.objectStore(Ne).get(st),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(pe).getAll(),o=r.objectStore(pe).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ne,st,n);for(let l=0;l<c.length;l++)await this.idbPut(pe,String(c[l]),a[l]);return indexedDB.deleteDatabase(yt),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(rn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(pe,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(pe,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(pe,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(pe)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const bt=crypto,ur=s=>s instanceof CryptoKey,nt=new TextEncoder,Ve=new TextDecoder;function sn(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const nn=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Te=s=>{let e=s;e instanceof Uint8Array&&(e=Ve.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return nn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Z extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Z.code="ERR_JOSE_GENERIC";class he extends Z{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class St extends Z{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}St.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 _e extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}_e.code="ERR_JOSE_NOT_SUPPORTED";class on extends Z{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}on.code="ERR_JWE_DECRYPTION_FAILED";class an extends Z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}an.code="ERR_JWE_INVALID";class Y extends Z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Y.code="ERR_JWS_INVALID";class ge extends Z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ge.code="ERR_JWT_INVALID";class cn extends Z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}cn.code="ERR_JWK_INVALID";class vt extends Z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}vt.code="ERR_JWKS_INVALID";class Et extends Z{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Et.code="ERR_JWKS_NO_MATCHING_KEY";class fr extends Z{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}fr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class pr extends Z{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}pr.code="ERR_JWKS_TIMEOUT";class _r extends Z{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}_r.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function xe(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function ze(s,e){return s.name===e}function It(s){return parseInt(s.name.slice(4),10)}function ln(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function dn(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function un(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!ze(s.algorithm,"HMAC"))throw xe("HMAC");const t=parseInt(e.slice(2),10);if(It(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ze(s.algorithm,"RSASSA-PKCS1-v1_5"))throw xe("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(It(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ze(s.algorithm,"RSA-PSS"))throw xe("RSA-PSS");const t=parseInt(e.slice(2),10);if(It(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw xe("Ed25519 or Ed448");break}case"Ed25519":{if(!ze(s.algorithm,"Ed25519"))throw xe("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!ze(s.algorithm,"ECDSA"))throw xe("ECDSA");const t=ln(e);if(s.algorithm.namedCurve!==t)throw xe(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}dn(s,r)}function gr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const xr=(s,...e)=>gr("Key must be ",s,...e);function mr(s,e,...r){return gr(`Key for the ${s} algorithm must be `,e,...r)}const wr=s=>ur(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",it=["CryptoKey"],hn=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function fn(s){return typeof s=="object"&&s!==null}function Se(s){if(!fn(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const pn=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function $e(s){return Se(s)&&typeof s.kty=="string"}function _n(s){return s.kty!=="oct"&&typeof s.d=="string"}function gn(s){return s.kty!=="oct"&&typeof s.d>"u"}function xn(s){return $e(s)&&s.kty==="oct"&&typeof s.k=="string"}function mn(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new _e('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const yr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=mn(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,bt.subtle.importKey("jwk",n,...t)},br=s=>Te(s);let We,Ue;const Sr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ot=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await yr({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},wn={normalizePublicKey:(s,e)=>{if(Sr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?br(r.k):(Ue||(Ue=new WeakMap),ot(Ue,s,r,e))}return $e(s)?s.k?Te(s.k):(Ue||(Ue=new WeakMap),ot(Ue,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Sr(s)){let r=s.export({format:"jwk"});return r.k?br(r.k):(We||(We=new WeakMap),ot(We,s,r,e))}return $e(s)?s.k?Te(s.k):(We||(We=new WeakMap),ot(We,s,s,e,!0)):s}};async function vr(s,e){if(!Se(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Te(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new _e('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return yr({...s,alg:e});default:throw new _e('Unsupported "kty" (Key Type) Parameter value')}}const He=s=>s==null?void 0:s[Symbol.toStringTag],At=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},yn=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&$e(e)){if(xn(e)&&At(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!wr(e))throw new TypeError(mr(s,e,...it,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${He(e)} instances for symmetric algorithms must be of type "secret"`)}},bn=(s,e,r,t)=>{if(t&&$e(e))switch(r){case"sign":if(_n(e)&&At(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(gn(e)&&At(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!wr(e))throw new TypeError(mr(s,e,...it,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${He(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${He(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${He(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${He(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${He(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Er(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?yn(e,r,t,s):bn(e,r,t,s)}Er.bind(void 0,!1);const Ir=Er.bind(void 0,!0);function Sn(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new _e(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const vn=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function En(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new _e(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function In(s,e,r){if(e=await wn.normalizePublicKey(e,s),ur(e))return un(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(xr(e,...it));return bt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(xr(e,...it,"Uint8Array","JSON Web Key"))}const An=async(s,e,r,t)=>{const n=await In(s,e,"verify");pn(s,n);const i=En(s,n.algorithm);try{return await bt.subtle.verify(i,n,r,t)}catch{return!1}};async function Tn(s,e,r){if(!Se(s))throw new Y("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new Y('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new Y("JWS Protected Header incorrect type");if(s.payload===void 0)throw new Y("JWS Payload missing");if(typeof s.signature!="string")throw new Y("JWS Signature missing or incorrect type");if(s.header!==void 0&&!Se(s.header))throw new Y("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const E=Te(s.protected);t=JSON.parse(Ve.decode(E))}catch{throw new Y("JWS Protected Header is invalid")}if(!hn(t,s.header))throw new Y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=Sn(Y,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Y('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&vn("algorithms",r.algorithms);if(c&&!c.has(a))throw new hr('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new Y("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new Y("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Ir(a,e,"verify"),$e(e)&&(e=await vr(e,a))):Ir(a,e,"verify");const u=sn(nt.encode(s.protected??""),nt.encode("."),typeof s.payload=="string"?nt.encode(s.payload):s.payload);let h;try{h=Te(s.signature)}catch{throw new Y("Failed to base64url decode the signature")}if(!await An(a,e,h,u))throw new _r;let p;if(o)try{p=Te(s.payload)}catch{throw new Y("Failed to base64url decode the payload")}else typeof s.payload=="string"?p=nt.encode(s.payload):p=s.payload;const w={payload:p};return s.protected!==void 0&&(w.protectedHeader=t),s.header!==void 0&&(w.unprotectedHeader=s.header),l?{...w,key:e}:w}async function Rn(s,e,r){if(s instanceof Uint8Array&&(s=Ve.decode(s)),typeof s!="string")throw new Y("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new Y("Invalid Compact JWS");const a=await Tn({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Pn=s=>Math.floor(s.getTime()/1e3),Ar=60,Tr=Ar*60,Tt=Tr*24,On=Tt*7,Cn=Tt*365.25,kn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Rr=s=>{const e=kn.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Ar);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Tr);break;case"day":case"days":case"d":n=Math.round(r*Tt);break;case"week":case"weeks":case"w":n=Math.round(r*On);break;default:n=Math.round(r*Cn);break}return e[1]==="-"||e[4]==="ago"?-n:n},Pr=s=>s.toLowerCase().replace(/^application\//,""),Nn=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Ln=(s,e,r={})=>{let t;try{t=JSON.parse(Ve.decode(e))}catch{}if(!Se(t))throw new ge("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Pr(s.typ)!==Pr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const w of new Set(u.reverse()))if(!(w in t))throw new he(`missing required "${w}" claim`,t,w,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Nn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=Rr(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=r,p=Pn(_||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>p+h)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=p-h)throw new St('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const w=p-t.iat,E=typeof l=="number"?l:Rr(l);if(w-h>E)throw new St('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(w<0-h)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Dn(s,e,r){var o;const t=await Rn(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new ge("JWTs MUST NOT use unencoded payload");const i={payload:Ln(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Mn(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new _e('Unsupported "alg" value for a JSON Web Key Set')}}function $n(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Wn)}function Wn(s){return Se(s)}function Or(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Un{constructor(e){if(this._cached=new WeakMap,!$n(e))throw new vt("JSON Web Key Set malformed");this._jwks=Or(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Mn(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Et;if(c!==1){const l=new fr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const h of o)try{yield await Cr(u,h,t)}catch{}},l}return Cr(this._cached,a,t)}}async function Cr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await vr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new vt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function kr(s){const e=new Un(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Or(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Hn=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new pr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new Z("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Z("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Bn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Rt;(typeof navigator>"u"||!((Ns=(xt=navigator.userAgent)==null?void 0:xt.startsWith)!=null&&Ns.call(xt,"Mozilla/5.0 ")))&&(Rt="jose/v5.10.0");const Pt=Symbol();function Fn(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!Se(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,Se))}class Kn{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Pt])!==void 0&&(this._cache=r==null?void 0:r[Pt],Fn(r==null?void 0:r[Pt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=kr(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Et&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Bn()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Rt&&!e.has("User-Agent")&&(e.set("User-Agent",Rt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Hn(this._url,this._timeoutDuration,this._options).then(r=>{this._local=kr(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Gn(s,e){const r=new Kn(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const qn=Te;function Jn(s){if(typeof s!="string")throw new ge("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new ge("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ge("Invalid JWT");if(!e)throw new ge("JWTs must contain a payload");let t;try{t=qn(e)}catch{throw new ge("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Ve.decode(t))}catch{throw new ge("Failed to parse the decoded payload as JSON")}if(!Se(n))throw new ge("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ot(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function ve(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function G(s,e,r=""){const t=Ot(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Nr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ve(s.outputLen),ve(s.blockLen)}function Be(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Lr(s,e){G(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Vn(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Fe(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Ct(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const zn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Yn(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function jn(s){for(let e=0;e<s.length;e++)s[e]=Yn(s[e]);return s}const Dr=zn?s=>s:jn,Mr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Xn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Ye(s){if(G(s),Mr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Xn[s[r]];return e}const Ee={_0:48,_9:57,A:65,F:70,a:97,f:102};function $r(s){if(s>=Ee._0&&s<=Ee._9)return s-Ee._0;if(s>=Ee.A&&s<=Ee.F)return s-(Ee.A-10);if(s>=Ee.a&&s<=Ee.f)return s-(Ee.a-10)}function at(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Mr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=$r(s.charCodeAt(i)),a=$r(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Re(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];G(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function Wr(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Ur(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const Zn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Qn(s,e,r){return s&e^~s&r}function ei(s,e,r){return s&e^s&r^e&r}class ti{constructor(e,r,t,n){T(this,"blockLen");T(this,"outputLen");T(this,"padOffset");T(this,"isLE");T(this,"buffer");T(this,"view");T(this,"finished",!1);T(this,"length",0);T(this,"pos",0);T(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Ct(this.buffer)}update(e){Be(this),G(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Ct(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Be(this),Lr(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Fe(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let h=o;h<n;h++)r[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Ct(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Pe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ct=BigInt(2**32-1),Hr=BigInt(32);function ri(s,e=!1){return e?{h:Number(s&ct),l:Number(s>>Hr&ct)}:{h:Number(s>>Hr&ct)|0,l:Number(s&ct)|0}}function si(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=ri(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const ni=(s,e,r)=>s<<r|e>>>32-r,ii=(s,e,r)=>e<<r|s>>>32-r,oi=(s,e,r)=>e<<r-32|s>>>64-r,ai=(s,e,r)=>s<<r-32|e>>>64-r,ci=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]),Oe=new Uint32Array(64);class li extends ti{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Oe[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const _=Oe[h-15],p=Oe[h-2],w=me(_,7)^me(_,18)^_>>>3,E=me(p,17)^me(p,19)^p>>>10;Oe[h]=E+Oe[h-7]+w+Oe[h-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const _=me(a,6)^me(a,11)^me(a,25),p=u+_+Qn(a,c,l)+ci[h]+Oe[h]|0,E=(me(t,2)^me(t,13)^me(t,22))+ei(t,n,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=n,n=t,t=p+E|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){Fe(Oe)}destroy(){this.set(0,0,0,0,0,0,0,0),Fe(this.buffer)}}class di extends li{constructor(){super(32);T(this,"A",Pe[0]|0);T(this,"B",Pe[1]|0);T(this,"C",Pe[2]|0);T(this,"D",Pe[3]|0);T(this,"E",Pe[4]|0);T(this,"F",Pe[5]|0);T(this,"G",Pe[6]|0);T(this,"H",Pe[7]|0)}}const ui=Wr(()=>new di,Zn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kt=BigInt(0),Nt=BigInt(1);function lt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Br(s){if(typeof s=="bigint"){if(!ht(s))throw new Error("positive bigint expected, got "+s)}else ve(s);return s}function dt(s){const e=Br(s).toString(16);return e.length&1?"0"+e:e}function Fr(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?kt:BigInt("0x"+s)}function ut(s){return Fr(Ye(s))}function Kr(s){return Fr(Ye(hi(G(s)).reverse()))}function Lt(s,e){ve(e),s=Br(s);const r=at(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Gr(s,e){return Lt(s,e).reverse()}function hi(s){return Uint8Array.from(s)}const ht=s=>typeof s=="bigint"&&kt<=s;function fi(s,e,r){return ht(s)&&ht(e)&&ht(r)&&e<=s&&s<r}function pi(s,e,r,t){if(!fi(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function _i(s){let e;for(e=0;s>kt;s>>=Nt,e+=1);return e}const Dt=s=>(Nt<<BigInt(s))-Nt;function gi(s,e,r){if(ve(s,"hashLen"),ve(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const h=()=>{c.fill(1),l.fill(0),u=0},_=(...y)=>r(l,Re(c,...y)),p=(y=n)=>{l=_(i,y),c=_(),y.length!==0&&(l=_(o,y),c=_())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const R=[];for(;y<e;){c=_();const N=c.slice();R.push(N),y+=c.length}return Re(...R)};return(y,R)=>{h(),p(y);let N;for(;!(N=R(w()));)p();return h(),N}}function Mt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function qr(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),ee=BigInt(1),Le=BigInt(2),Jr=BigInt(3),Vr=BigInt(4),zr=BigInt(5),xi=BigInt(7),Yr=BigInt(8),mi=BigInt(9),jr=BigInt(16);function fe(s,e){const r=s%e;return r>=ae?r:e+r}function de(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function Xr(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=fe(s,e),t=e,n=ae,i=ee;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==ee)throw new Error("invert: does not exist");return fe(n,e)}function $t(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Zr(s,e){const r=(s.ORDER+ee)/Vr,t=s.pow(e,r);return $t(s,t,e),t}function wi(s,e){const r=(s.ORDER-zr)/Yr,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return $t(s,a,e),a}function yi(s){const e=ft(s),r=Qr(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+xi)/jr;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const h=a.mul(l,n),_=a.mul(l,i),p=a.eql(a.sqr(u),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(_,h,w);const E=a.eql(a.sqr(u),c),y=a.cmov(l,u,E);return $t(a,y,c),y}}function Qr(s){if(s<Jr)throw new Error("sqrt is not defined for small field");let e=s-ee,r=0;for(;e%Le===ae;)e/=Le,r++;let t=Le;const n=ft(s);for(;ts(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Zr;let i=n.pow(t,e);const o=(e+ee)/Le;return function(c,l){if(c.is0(l))return l;if(ts(c,l)!==1)throw new Error("Cannot find square root");let u=r,h=c.mul(c.ONE,i),_=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let w=1,E=c.sqr(_);for(;!c.eql(E,c.ONE);)if(w++,E=c.sqr(E),w===u)throw new Error("Cannot find square root");const y=ee<<BigInt(u-w-1),R=c.pow(h,y);u=w,h=c.sqr(R),_=c.mul(_,h),p=c.mul(p,R)}return p}}function bi(s){return s%Vr===Jr?Zr:s%Yr===zr?wi:s%jr===mi?yi(s):Qr(s)}const Si=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vi(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Si.reduce((t,n)=>(t[n]="function",t),e);return Mt(s,r),s}function Ei(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===ee)return e;let t=s.ONE,n=e;for(;r>ae;)r&ee&&(t=s.mul(t,n)),n=s.sqr(n),r>>=ee;return t}function es(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function ts(s,e){const r=(s.ORDER-ee)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Ii(s,e){e!==void 0&&ve(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Ai{constructor(e,r={}){T(this,"ORDER");T(this,"BITS");T(this,"BYTES");T(this,"isLE");T(this,"ZERO",ae);T(this,"ONE",ee);T(this,"_lengths");T(this,"_sqrt");T(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Ii(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return fe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return fe(e*e,this.ORDER)}add(e,r){return fe(e+r,this.ORDER)}sub(e,r){return fe(e-r,this.ORDER)}mul(e,r){return fe(e*r,this.ORDER)}pow(e,r){return Ei(this,e,r)}div(e,r){return fe(e*Xr(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return Xr(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=bi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Gr(e,this.BYTES):Lt(e,this.BYTES)}fromBytes(e,r=!1){G(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Kr(e):ut(e);if(a&&(c=fe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return es(this,e)}cmov(e,r,t){return t?r:e}}function ft(s,e={}){return new Ai(s,e)}function rs(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function ss(s){const e=rs(s);return e+Math.ceil(e/2)}function Ti(s,e,r=!1){G(s);const t=s.length,n=rs(e),i=ss(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?Kr(s):ut(s),a=fe(o,e-ee)+ee;return r?Gr(a,n):Lt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ke=BigInt(0),De=BigInt(1);function pt(s,e){const r=e.negate();return s?r:e}function ns(s,e){const r=es(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function is(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Wt(s,e){is(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Dt(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function os(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,h=a===0,_=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:_,isNegF:p,offsetF:l}}const Ut=new WeakMap,as=new WeakMap;function Ht(s){return as.get(s)||1}function cs(s){if(s!==Ke)throw new Error("invalid wNAF")}class Ri{constructor(e,r){T(this,"BASE");T(this,"ZERO");T(this,"Fn");T(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>Ke;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Wt(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Wt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:_,offsetF:p}=os(t,a,o);t=c,u?i=i.add(pt(_,r[p])):n=n.add(pt(h,r[l]))}return cs(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Wt(e,this.bits);for(let o=0;o<i.windows&&t!==Ke;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=os(t,o,i);if(t=a,!l){const h=r[c];n=n.add(u?h.negate():h)}}return cs(t),n}getPrecomputes(e,r,t){let n=Ut.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Ut.set(r,n))),n}cached(e,r,t){const n=Ht(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=Ht(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){is(r,this.bits),as.set(e,r),Ut.delete(e)}hasCache(e){return Ht(e)!==1}}function Pi(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>Ke||t>Ke;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function ls(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vi(e),e}else return ft(s,{isLE:r})}function Oi(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ke))throw new Error(`CURVE.${c} must be positive bigint`)}const n=ls(e.p,r.Fp,t),i=ls(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Ci(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class ds{constructor(e,r){T(this,"oHash");T(this,"iHash");T(this,"blockLen");T(this,"outputLen");T(this,"finished",!1);T(this,"destroyed",!1);if(Nr(e),G(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Fe(n)}update(e){return Be(this),this.iHash.update(e),this}digestInto(e){Be(this),G(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const us=(s,e,r)=>new ds(s,e).update(r).digest();us.create=(s,e)=>new ds(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hs=(s,e)=>(s+(s>=0?e:-e)/fs)/e;function ki(s,e,r){const[[t,n],[i,o]]=e,a=hs(o*s,r),c=hs(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const h=l<Ie,_=u<Ie;h&&(l=-l),_&&(u=-u);const p=Dt(Math.ceil(_i(r)/2))+Ge;if(l<Ie||l>=p||u<Ie||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:l,k2neg:_,k2:u}}function Bt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Ft(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return lt(r.lowS,"lowS"),lt(r.prehash,"prehash"),r.format!==void 0&&Bt(r.format),r}class Ni extends Error{constructor(e=""){super(e)}}const Ce={Err:Ni,_tlv:{encode:(s,e)=>{const{Err:r}=Ce;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=dt(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?dt(n.length/2|128):"";return dt(s)+i+n+e},decode(s,e){const{Err:r}=Ce;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=Ce;if(s<Ie)throw new e("integer: negative integers are not allowed");let r=dt(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Ce;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ut(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Ce,n=G(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Ce,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Ge=BigInt(1),fs=BigInt(2),_t=BigInt(3),Li=BigInt(4);function Di(s,e={}){const r=Oi("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Mt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=_s(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(I,x,m){const{x:v,y:A}=x.toAffine(),k=t.toBytes(v);if(lt(m,"isCompressed"),m){u();const C=!t.isOdd(A);return Re(ps(C),k)}else return Re(Uint8Array.of(4),k,t.toBytes(A))}function _(I){G(I,void 0,"Point");const{publicKey:x,publicKeyUncompressed:m}=l,v=I.length,A=I[0],k=I.subarray(1);if(v===x&&(A===2||A===3)){const C=t.fromBytes(k);if(!t.isValid(C))throw new Error("bad point: is not on curve, wrong x");const L=E(C);let O;try{O=t.sqrt(L)}catch(j){const K=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}u();const D=t.isOdd(O);return(A&1)===1!==D&&(O=t.neg(O)),{x:C,y:O}}else if(v===m&&A===4){const C=t.BYTES,L=t.fromBytes(k.subarray(0,C)),O=t.fromBytes(k.subarray(C,C*2));if(!y(L,O))throw new Error("bad point: is not on curve");return{x:L,y:O}}else throw new Error(`bad point: got length ${v}, expected compressed=${x} or uncompressed=${m}`)}const p=e.toBytes||h,w=e.fromBytes||_;function E(I){const x=t.sqr(I),m=t.mul(x,I);return t.add(t.add(m,t.mul(I,i.a)),i.b)}function y(I,x){const m=t.sqr(x),v=E(I);return t.eql(m,v)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const R=t.mul(t.pow(i.a,_t),Li),N=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(R,N)))throw new Error("bad curve params: a or b");function B(I,x,m=!1){if(!t.isValid(x)||m&&t.is0(x))throw new Error(`bad point coordinate ${I}`);return x}function M(I){if(!(I instanceof z))throw new Error("Weierstrass Point expected")}function V(I){if(!c||!c.basises)throw new Error("no endo");return ki(I,c.basises,n.ORDER)}const F=qr((I,x)=>{const{X:m,Y:v,Z:A}=I;if(t.eql(A,t.ONE))return{x:m,y:v};const k=I.is0();x==null&&(x=k?t.ONE:t.inv(A));const C=t.mul(m,x),L=t.mul(v,x),O=t.mul(A,x);if(k)return{x:t.ZERO,y:t.ZERO};if(!t.eql(O,t.ONE))throw new Error("invZ was invalid");return{x:C,y:L}}),ne=qr(I=>{if(I.is0()){if(e.allowInfinityPoint&&!t.is0(I.Y))return;throw new Error("bad point: ZERO")}const{x,y:m}=I.toAffine();if(!t.isValid(x)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(x,m))throw new Error("bad point: equation left != right");if(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function H(I,x,m,v,A){return m=new z(t.mul(m.X,I),m.Y,m.Z),x=pt(v,x),m=pt(A,m),x.add(m)}const S=class S{constructor(x,m,v){T(this,"X");T(this,"Y");T(this,"Z");this.X=B("x",x),this.Y=B("y",m,!0),this.Z=B("z",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){const{x:m,y:v}=x||{};if(!x||!t.isValid(m)||!t.isValid(v))throw new Error("invalid affine point");if(x instanceof S)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(v)?S.ZERO:new S(m,v,t.ONE)}static fromBytes(x){const m=S.fromAffine(w(G(x,void 0,"point")));return m.assertValidity(),m}static fromHex(x){return S.fromBytes(at(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,m=!0){return b.createCache(this,x),m||this.multiply(_t),this}assertValidity(){ne(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:m,Y:v,Z:A}=this,{X:k,Y:C,Z:L}=x,O=t.eql(t.mul(m,L),t.mul(k,A)),D=t.eql(t.mul(v,L),t.mul(C,A));return O&&D}negate(){return new S(this.X,t.neg(this.Y),this.Z)}double(){const{a:x,b:m}=i,v=t.mul(m,_t),{X:A,Y:k,Z:C}=this;let L=t.ZERO,O=t.ZERO,D=t.ZERO,U=t.mul(A,A),j=t.mul(k,k),K=t.mul(C,C),W=t.mul(A,k);return W=t.add(W,W),D=t.mul(A,C),D=t.add(D,D),L=t.mul(x,D),O=t.mul(v,K),O=t.add(L,O),L=t.sub(j,O),O=t.add(j,O),O=t.mul(L,O),L=t.mul(W,L),D=t.mul(v,D),K=t.mul(x,K),W=t.sub(U,K),W=t.mul(x,W),W=t.add(W,D),D=t.add(U,U),U=t.add(D,U),U=t.add(U,K),U=t.mul(U,W),O=t.add(O,U),K=t.mul(k,C),K=t.add(K,K),U=t.mul(K,W),L=t.sub(L,U),D=t.mul(K,j),D=t.add(D,D),D=t.add(D,D),new S(L,O,D)}add(x){M(x);const{X:m,Y:v,Z:A}=this,{X:k,Y:C,Z:L}=x;let O=t.ZERO,D=t.ZERO,U=t.ZERO;const j=i.a,K=t.mul(i.b,_t);let W=t.mul(m,k),Q=t.mul(v,C),ie=t.mul(A,L),le=t.add(m,v),q=t.add(k,C);le=t.mul(le,q),q=t.add(W,Q),le=t.sub(le,q),q=t.add(m,A);let oe=t.add(k,L);return q=t.mul(q,oe),oe=t.add(W,ie),q=t.sub(q,oe),oe=t.add(v,A),O=t.add(C,L),oe=t.mul(oe,O),O=t.add(Q,ie),oe=t.sub(oe,O),U=t.mul(j,q),O=t.mul(K,ie),U=t.add(O,U),O=t.sub(Q,U),U=t.add(Q,U),D=t.mul(O,U),Q=t.add(W,W),Q=t.add(Q,W),ie=t.mul(j,ie),q=t.mul(K,q),Q=t.add(Q,ie),ie=t.sub(W,ie),ie=t.mul(j,ie),q=t.add(q,ie),W=t.mul(Q,q),D=t.add(D,W),W=t.mul(oe,q),O=t.mul(le,O),O=t.sub(O,W),W=t.mul(le,Q),U=t.mul(oe,U),U=t.add(U,W),new S(O,D,U)}subtract(x){return this.add(x.negate())}is0(){return this.equals(S.ZERO)}multiply(x){const{endo:m}=e;if(!n.isValidNot0(x))throw new Error("invalid scalar: out of range");let v,A;const k=C=>b.cached(this,C,L=>ns(S,L));if(m){const{k1neg:C,k1:L,k2neg:O,k2:D}=V(x),{p:U,f:j}=k(L),{p:K,f:W}=k(D);A=j.add(W),v=H(m.beta,U,K,C,O)}else{const{p:C,f:L}=k(x);v=C,A=L}return ns(S,[v,A])[0]}multiplyUnsafe(x){const{endo:m}=e,v=this;if(!n.isValid(x))throw new Error("invalid scalar: out of range");if(x===Ie||v.is0())return S.ZERO;if(x===Ge)return v;if(b.hasCache(this))return this.multiply(x);if(m){const{k1neg:A,k1:k,k2neg:C,k2:L}=V(x),{p1:O,p2:D}=Pi(S,v,k,L);return H(m.beta,O,D,A,C)}else return b.unsafe(v,x)}toAffine(x){return F(this,x)}isTorsionFree(){const{isTorsionFree:x}=e;return o===Ge?!0:x?x(S,this):b.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=e;return o===Ge?this:x?x(S,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(x=!0){return lt(x,"isCompressed"),this.assertValidity(),p(S,this,x)}toHex(x=!0){return Ye(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};T(S,"BASE",new S(i.Gx,i.Gy,t.ONE)),T(S,"ZERO",new S(t.ZERO,t.ONE,t.ZERO)),T(S,"Fp",t),T(S,"Fn",n);let z=S;const P=n.BITS,b=new Ri(z,e.endo?Math.ceil(P/2):P);return z.BASE.precompute(8),z}function ps(s){return Uint8Array.of(s?2:3)}function _s(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Mi(s,e={}){const{Fn:r}=s,t=e.randomBytes||Ur,n=Object.assign(_s(s.Fp,r),{seed:ss(r.ORDER)});function i(p){try{const w=r.fromBytes(p);return r.isValidNot0(w)}catch{return!1}}function o(p,w){const{publicKey:E,publicKeyUncompressed:y}=n;try{const R=p.length;return w===!0&&R!==E||w===!1&&R!==y?!1:!!s.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Ti(G(p,n.seed,"seed"),r.ORDER)}function c(p,w=!0){return s.BASE.multiply(r.fromBytes(p)).toBytes(w)}function l(p){const{secretKey:w,publicKey:E,publicKeyUncompressed:y}=n;if(!Ot(p)||"_lengths"in r&&r._lengths||w===E)return;const R=G(p,void 0,"key").length;return R===E||R===y}function u(p,w,E=!0){if(l(p)===!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=r.fromBytes(p);return s.fromBytes(w).multiply(y).toBytes(E)}const h={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=Ci(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:s,utils:h,lengths:n})}function $i(s,e,r={}){Nr(e),Mt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Ur,n=r.hmac||((x,m)=>us(e,x,m)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:p}=Mi(s,r),w={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},E=a*fs<i.ORDER;function y(x){const m=a>>Ge;return x>m}function R(x,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return m}function N(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(x,m){Bt(m);const v=p.signature,A=m==="compact"?v:m==="recovered"?v+1:void 0;return G(x,A)}class M{constructor(m,v,A){T(this,"r");T(this,"s");T(this,"recovery");if(this.r=R("r",m),this.s=R("s",v),A!=null){if(N(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(m,v=w.format){B(m,v);let A;if(v==="der"){const{r:O,s:D}=Ce.toSig(G(m));return new M(O,D)}v==="recovered"&&(A=m[0],v="compact",m=m.subarray(1));const k=p.signature/2,C=m.subarray(0,k),L=m.subarray(k,k*2);return new M(o.fromBytes(C),o.fromBytes(L),A)}static fromHex(m,v){return this.fromBytes(at(m),v)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new M(this.r,this.s,m)}recoverPublicKey(m){const{r:v,s:A}=this,k=this.assertRecovery(),C=k===2||k===3?v+a:v;if(!i.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const L=i.toBytes(C),O=s.fromBytes(Re(ps((k&1)===0),L)),D=o.inv(C),U=F(G(m,void 0,"msgHash")),j=o.create(-U*D),K=o.create(A*D),W=s.BASE.multiplyUnsafe(j).add(O.multiplyUnsafe(K));if(W.is0())throw new Error("invalid recovery: point at infinify");return W.assertValidity(),W}hasHighS(){return y(this.s)}toBytes(m=w.format){if(Bt(m),m==="der")return at(Ce.hexFromSig(this));const{r:v,s:A}=this,k=o.toBytes(v),C=o.toBytes(A);return m==="recovered"?(N(),Re(Uint8Array.of(this.assertRecovery()),k,C)):Re(k,C)}toHex(m){return Ye(this.toBytes(m))}}const V=r.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const v=ut(m),A=m.length*8-c;return A>0?v>>BigInt(A):v},F=r.bits2int_modN||function(m){return o.create(V(m))},ne=Dt(c);function H(x){return pi("num < 2^"+c,x,Ie,ne),o.toBytes(x)}function z(x,m){return G(x,void 0,"message"),m?G(e(x),void 0,"prehashed message"):x}function P(x,m,v){const{lowS:A,prehash:k,extraEntropy:C}=Ft(v,w);x=z(x,k);const L=F(x),O=o.fromBytes(m);if(!o.isValidNot0(O))throw new Error("invalid private key");const D=[H(O),H(L)];if(C!=null&&C!==!1){const W=C===!0?t(p.secretKey):C;D.push(G(W,void 0,"extraEntropy"))}const U=Re(...D),j=L;function K(W){const Q=V(W);if(!o.isValidNot0(Q))return;const ie=o.inv(Q),le=s.BASE.multiply(Q).toAffine(),q=o.create(le.x);if(q===Ie)return;const oe=o.create(ie*o.create(j+q*O));if(oe===Ie)return;let Ls=(le.x===q?0:2)|Number(le.y&Ge),Ds=oe;return A&&y(oe)&&(Ds=o.neg(oe),Ls^=1),new M(q,Ds,E?void 0:Ls)}return{seed:U,k2sig:K}}function b(x,m,v={}){const{seed:A,k2sig:k}=P(x,m,v);return gi(e.outputLen,o.BYTES,n)(A,k).toBytes(v.format)}function S(x,m,v,A={}){const{lowS:k,prehash:C,format:L}=Ft(A,w);if(v=G(v,void 0,"publicKey"),m=z(m,C),!Ot(x)){const O=x instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+O)}B(x,L);try{const O=M.fromBytes(x,L),D=s.fromBytes(v);if(k&&O.hasHighS())return!1;const{r:U,s:j}=O,K=F(m),W=o.inv(j),Q=o.create(K*W),ie=o.create(U*W),le=s.BASE.multiplyUnsafe(Q).add(D.multiplyUnsafe(ie));return le.is0()?!1:o.create(le.x)===U}catch{return!1}}function I(x,m,v={}){const{prehash:A}=Ft(v,w);return m=z(m,A),M.fromBytes(x,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:_,lengths:p,Point:s,sign:b,verify:S,recoverPublicKey:I,Signature:M,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Wi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},gs=BigInt(2);function Ui(s){const e=Kt.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,h=de(u,r,e)*u%e,_=de(h,r,e)*u%e,p=de(_,gs,e)*l%e,w=de(p,n,e)*p%e,E=de(w,i,e)*w%e,y=de(E,a,e)*E%e,R=de(y,c,e)*y%e,N=de(R,a,e)*E%e,B=de(N,r,e)*u%e,M=de(B,o,e)*w%e,V=de(M,t,e)*l%e,F=de(V,gs,e);if(!Gt.eql(Gt.sqr(F),s))throw new Error("Cannot find square root");return F}const Gt=ft(Kt.p,{sqrt:Ui}),Hi=$i(Di(Kt,{Fp:Gt,endo:Wi}),ui),Bi=BigInt(0),je=BigInt(1),Fi=BigInt(2),Ki=BigInt(7),Gi=BigInt(256),qi=BigInt(113),xs=[],ms=[],ws=[];for(let s=0,e=je,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],xs.push(2*(5*t+r)),ms.push((s+1)*(s+2)/2%64);let n=Bi;for(let i=0;i<7;i++)e=(e<<je^(e>>Ki)*qi)%Gi,e&Fi&&(n^=je<<(je<<BigInt(i))-je);ws.push(n)}const ys=si(ws,!0),Ji=ys[0],Vi=ys[1],bs=(s,e,r)=>r>32?oi(s,e,r):ni(s,e,r),Ss=(s,e,r)=>r>32?ai(s,e,r):ii(s,e,r);function zi(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=bs(l,u,1)^r[a],_=Ss(l,u,1)^r[a+1];for(let p=0;p<50;p+=10)s[o+p]^=h,s[o+p+1]^=_}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=ms[o],c=bs(n,i,a),l=Ss(n,i,a),u=xs[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Ji[t],s[1]^=Vi[t]}Fe(r)}class qt{constructor(e,r,t,n=!1,i=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,ve(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Vn(this.state)}clone(){return this._cloneInto()}keccak(){Dr(this.state32),zi(this.state32,this.rounds),Dr(this.state32),this.posOut=0,this.pos=0}update(e){Be(this),G(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Be(this,!1),G(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ve(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Lr(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,Fe(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new qt(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const vs=((s,e,r,t={})=>Wr(()=>new qt(e,s,r),t))(1,136,32),Yi=60;class ji{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Gn(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Yi<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Dn(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Jn(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
12
|
+
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=vs(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Xi(a),l=c.slice(0,32),u=c.slice(32,64),h=c[64],_=h>=27?h-27:h,E=new Hi.Signature(Es(l),Es(u)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),y=vs(E);return"0x"+Ye(y.slice(12))}}function Xi(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Es(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Zi=3e4,Qi=1e3;class eo{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,Qi*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Zi);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const to=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Me{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Me.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Me.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Me.generateRandom16Hex(),l=Me.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const _=window.open(h,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),M(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,E=30;let y=0,R=null;const N=()=>{clearInterval(B),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),R=setTimeout(()=>{M(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},B=setInterval(()=>{y++;try{_.closed&&(y<=w?N():(M(),t(new Error("로그인이 취소되었습니다"))))}catch{N()}},1e3),M=()=>{clearTimeout(p),clearInterval(B),R&&clearTimeout(R),window.removeEventListener("message",V)},V=F=>{if(F.origin!==e.expectedOrigin)return;if(!to.has(F.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",F.origin),M(),t(new Error("Unauthorized OAuth origin"));return}M();const ne=typeof F.data.status=="string",H=ne?F.data.data??{}:F.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:ne?"wrapped":"flat",status:ne?F.data.status:"(flat)"});const z=(H==null?void 0:H.state)??F.data.state;if(!z||z!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ne&&F.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",H==null?void 0:H.error),t(new Error((H==null?void 0:H.error)||"Authentication failed"));return}if(!ne&&(H!=null&&H.error)){d.error("[CROSSx] OAuth 실패:",H.error),t(new Error(H.error||"Authentication failed"));return}const P=H==null?void 0:H.idToken,b=H==null?void 0:H.accessToken,S=b??P;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!b,hasIdToken:!!P}),!S){d.error("[CROSSx] 토큰을 찾을 수 없음:",F.data),t(new Error("Token not found in response"));return}const I=x=>{Me.verifyIdTokenNonce(x,l).then(()=>r(S)).catch(m=>{d.error("[CROSSx] nonce 검증 실패:",m),t(m instanceof Error?m:new Error("nonce verification failed"))})};b?b.split(".").length===3?I(b):P?I(P):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(S)):P?I(P):t(new Error("Token not found in response"))};window.addEventListener("message",V)})}}const Xe="crossx_wallet_data",qe="crossx_mock_pin_hash";class ro{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(Xe)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(Xe);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(Xe,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(qe,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(f.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(Xe);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(qe);return r&&r!==e?!1:(r||await this.storage.set(qe,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(f.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(qe);if(n&&t&&n!==t)throw new g(f.PIN_WRONG,"Incorrect PIN.");await this.storage.set(qe,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new g(f.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new g(f.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Xe,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(qe,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Je{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(lr))return e;const r=!e||this.tokenStore.isExpiringSoon(lr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new g(f.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(f.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const _=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(_&&typeof _.code=="number"){if(_.code<0||_.code>=400){const p=_.message||_.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:_.code,message:p,url:o,method:e});const w=Je.mapGatewayError(_.code,_.data);if(w===f.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new g(f.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}const E=w===f.AUTH_NOT_AUTHENTICATED?f.SESSION_EXPIRED:w,y=E===f.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":Je.getGatewayErrorMessage(_.code,p),R=_.data,N=w===f.PIN_LOCKED?Je.extractLockDetails(R):R??void 0;throw new g(E,y,N)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:_.code,url:o,method:e}),_.data??_}return _}catch(h){if(h instanceof g)throw h;const _=((c=h.response)==null?void 0:c.status)??h.status;if((_===401||_===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${_} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new g(f.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((l=h.response)!=null&&l.data){const p=h.response.data,w=p.message||p.data||"API 요청에 실패했습니다",E=p.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:w,url:o,method:e,status:(u=h.response)==null?void 0:u.status}),new g(f.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${w}`)}throw h}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(f.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new g(f.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new g(f.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new g(f.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e};return(await this.request("POST","/mnemonic/verify-password",r)).valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(f.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return f.AUTH_NOT_AUTHENTICATED;case-10001:return f.UNKNOWN_ERROR;case-10006:return f.GATEWAY_INTERNAL_ERROR;case-10007:return f.BROADCAST_FAILED;case-10008:return f.GATEWAY_LOCK_CONFLICT;case-10004:return f.WALLET_ALREADY_EXISTS;case-10005:return f.WALLET_NOT_FOUND;case-10011:return f.WALLET_NOT_FOUND;case-10030:return f.WALLET_INCONSISTENT_STATE;case-10010:return f.MIGRATION_FAILED;case-10012:return f.MIGRATION_BACKUP_EXISTS;case-10013:return f.WITHDRAW_FAILED;case-10027:return f.MIGRATION_PIN_LOCKED;case-10022:return f.PROJECT_NOT_REGISTERED;case-10023:return f.PROJECT_ID_MISSING;case-10024:return f.ORIGIN_NOT_ALLOWED;case-10025:return f.INVALID_APP_TYPE;case-10028:return Je.hasLockInfo(r)?f.PIN_LOCKED:f.PIN_WRONG;case-10029:return f.PIN_INVALID;case-10031:return f.PIN_LOCKED;case-10032:return f.PIN_REPEATED_PATTERN;case-10026:return f.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return f.PREPARE_FAILED;case-10016:return f.PREPARE_EXPIRED;case-10017:case-10018:return f.PREPARE_MISMATCH;case-10020:return f.CHAIN_NOT_SUPPORTED;case-10021:return f.INVALID_CHAIN;case-10040:return f.HMAC_REQUIRED;case-10041:return f.HMAC_VERIFICATION_FAILED;default:return f.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class Ze{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}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 r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=Ze.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?Qs:Zs;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new g(Ze.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=Ze.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new g(f.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Qe).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return f.CHAIN_NOT_SUPPORTED;case-10021:return f.INVALID_CHAIN;case-10022:return f.PROJECT_NOT_REGISTERED;case-10023:return f.PROJECT_ID_MISSING;case-10024:return f.APP_IDENTIFIER_MISSING;case-10025:return f.INVALID_APP_TYPE;default:return f.UNKNOWN_ERROR}}}const Is="__crossx-confirm-style",te="__crossx-confirm-overlay",so={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 As(s,e){const r=so[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const no=`
|
|
3
13
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
4
14
|
|
|
5
|
-
#${
|
|
15
|
+
#${te} {
|
|
6
16
|
position: fixed;
|
|
7
17
|
inset: 0;
|
|
8
18
|
z-index: 2147483647;
|
|
@@ -1166,6 +1176,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1166
1176
|
max-height: 320px;
|
|
1167
1177
|
overflow-y: auto;
|
|
1168
1178
|
-webkit-overflow-scrolling: touch;
|
|
1179
|
+
overscroll-behavior: contain;
|
|
1180
|
+
touch-action: pan-y;
|
|
1169
1181
|
scrollbar-width: thin;
|
|
1170
1182
|
}
|
|
1171
1183
|
.__crossx-wallet-list::-webkit-scrollbar {
|
|
@@ -1268,7 +1280,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1268
1280
|
|
|
1269
1281
|
/* ── Mobile bottom sheet ───────────────────────────────────── */
|
|
1270
1282
|
@media (max-width: 480px) {
|
|
1271
|
-
#${
|
|
1283
|
+
#${te} { align-items: flex-end; }
|
|
1272
1284
|
.__crossx-card {
|
|
1273
1285
|
width: 100%;
|
|
1274
1286
|
max-width: 100%;
|
|
@@ -1280,8 +1292,37 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1280
1292
|
}
|
|
1281
1293
|
.__crossx-card--wallet-selector {
|
|
1282
1294
|
overflow: hidden !important;
|
|
1295
|
+
display: flex !important;
|
|
1296
|
+
flex-direction: column !important;
|
|
1297
|
+
}
|
|
1298
|
+
.__crossx-card--wallet-selector .__crossx-header { flex-shrink: 0; }
|
|
1299
|
+
.__crossx-card--wallet-selector > .__crossx-divider { flex-shrink: 0; }
|
|
1300
|
+
.__crossx-card--wallet-selector .__crossx-body {
|
|
1301
|
+
flex: 1;
|
|
1302
|
+
min-height: 0;
|
|
1303
|
+
overflow: hidden;
|
|
1304
|
+
display: flex;
|
|
1305
|
+
flex-direction: column;
|
|
1306
|
+
}
|
|
1307
|
+
.__crossx-card--wallet-selector .__crossx-body-cols {
|
|
1308
|
+
flex: 1;
|
|
1309
|
+
min-height: 0;
|
|
1310
|
+
display: flex;
|
|
1311
|
+
flex-direction: column;
|
|
1312
|
+
}
|
|
1313
|
+
.__crossx-card--wallet-selector .__crossx-col-left { flex-shrink: 0; }
|
|
1314
|
+
.__crossx-card--wallet-selector .__crossx-col-right-ws {
|
|
1315
|
+
flex: 1;
|
|
1316
|
+
min-height: 0;
|
|
1317
|
+
display: flex;
|
|
1318
|
+
flex-direction: column;
|
|
1283
1319
|
}
|
|
1284
|
-
.__crossx-card--wallet-selector .__crossx-wallet-list {
|
|
1320
|
+
.__crossx-card--wallet-selector .__crossx-wallet-list {
|
|
1321
|
+
flex: 1;
|
|
1322
|
+
min-height: 0;
|
|
1323
|
+
max-height: 203px;
|
|
1324
|
+
}
|
|
1325
|
+
.__crossx-card--wallet-selector .__crossx-wallet-add { flex-shrink: 0; }
|
|
1285
1326
|
.__crossx-card--send-tx,
|
|
1286
1327
|
.__crossx-card--sign-tx,
|
|
1287
1328
|
.__crossx-card--sign-msg,
|
|
@@ -1407,7 +1448,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1407
1448
|
|
|
1408
1449
|
/* ── Landscape for signing/transaction modals ──────────── */
|
|
1409
1450
|
@media (orientation: landscape) and (max-height: 500px) {
|
|
1410
|
-
#${
|
|
1451
|
+
#${te} { align-items: center !important; overflow: hidden; }
|
|
1411
1452
|
.__crossx-card--send-tx,
|
|
1412
1453
|
.__crossx-card--sign-tx,
|
|
1413
1454
|
.__crossx-card--sign-msg,
|
|
@@ -1704,6 +1745,24 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1704
1745
|
flex-shrink: 0;
|
|
1705
1746
|
color: var(--cx-error);
|
|
1706
1747
|
}
|
|
1748
|
+
/* 시도 횟수 카운트 (X/Y) */
|
|
1749
|
+
.__crossx-pin6-attempt {
|
|
1750
|
+
font-size: 16px;
|
|
1751
|
+
font-weight: 500;
|
|
1752
|
+
line-height: 1.5;
|
|
1753
|
+
color: var(--cx-error);
|
|
1754
|
+
text-align: center;
|
|
1755
|
+
letter-spacing: -0.16px;
|
|
1756
|
+
margin: 0;
|
|
1757
|
+
}
|
|
1758
|
+
.__crossx-pin6-warning {
|
|
1759
|
+
font-size: 14px;
|
|
1760
|
+
font-weight: 500;
|
|
1761
|
+
line-height: 1.5;
|
|
1762
|
+
color: var(--cx-error);
|
|
1763
|
+
text-align: center;
|
|
1764
|
+
margin: 0;
|
|
1765
|
+
}
|
|
1707
1766
|
/* Next 버튼 */
|
|
1708
1767
|
.__crossx-pin6-next {
|
|
1709
1768
|
width: 100%;
|
|
@@ -1724,31 +1783,31 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1724
1783
|
opacity: 0.5;
|
|
1725
1784
|
cursor: default;
|
|
1726
1785
|
}
|
|
1727
|
-
`;function we(){let s=document.getElementById(
|
|
1786
|
+
`;function we(){let s=document.getElementById(Is);s||(s=document.createElement("style"),s.id=Is,document.head.appendChild(s)),s.textContent=no}function ye(s){const e=r=>r.stopPropagation();for(const r of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(r,e);s.setAttribute("data-vaul-no-drag","");for(const r of["touchstart","touchend"])s.addEventListener(r,e);s.addEventListener("touchmove",r=>{r.stopPropagation();let t=r.target;for(;t&&t!==s;){const n=window.getComputedStyle(t);if((n.overflowY==="auto"||n.overflowY==="scroll")&&t.scrollHeight>t.clientHeight)return;t=t.parentElement}r.preventDefault()},{passive:!1}),document.body.appendChild(s)}const io=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Jt(){if(io()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function re(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function oo(s,e="CROSS",r=18){if(!s||s==="0x"||s==="0x0")return null;try{const t=BigInt(s);if(t===0n)return null;const n=Vt(t,r);return n==="0"?null:`${n} ${e}`}catch{return null}}const Ts={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 Rs(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&Ts[e]?Ts[e]:s}function Vt(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,o=(s%r).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function zt(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function ao(s){try{return BigInt(s).toLocaleString()}catch{return s}}function co(s){const{gasLimit:e,gasPrice:r,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=18}=s;if(!e)return null;try{const a=BigInt(e),c=ao(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${Vt(l,o)} ${i}`,maxFeeGwei:zt(t),maxPriorityFeeGwei:n?zt(n):void 0,gasLimitFormatted:c}}if(r){const l=a*BigInt(r);return{isDynamic:!1,estTxFee:`${Vt(l,o)} ${i}`,gasPriceGwei:zt(r),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ps(s){const e=co(s);if(!e)return J("Estimated fee","<span>—</span>");let r=J("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(r+=J("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(r+=J("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(r+=J("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(r+=J("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),r}const Ae=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1728
1787
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1729
1788
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1730
1789
|
</svg>`,ce=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
1731
1790
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
1732
1791
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
1733
|
-
</svg>`,
|
|
1792
|
+
</svg>`,lo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1734
1793
|
<circle cx="20" cy="20" r="20" fill="#00D5AA"/>
|
|
1735
1794
|
<path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/>
|
|
1736
|
-
</svg>`,
|
|
1795
|
+
</svg>`,Yt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
|
1737
1796
|
<rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
|
|
1738
1797
|
<path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
|
|
1739
1798
|
<rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
|
|
1740
|
-
</svg>`,
|
|
1799
|
+
</svg>`,uo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
1741
1800
|
<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)"/>
|
|
1742
|
-
</svg>`,
|
|
1801
|
+
</svg>`,ho=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
1743
1802
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
1744
1803
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
1745
1804
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
1746
|
-
</svg>`;function ue(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function
|
|
1805
|
+
</svg>`;function ue(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function J(s,e){return`
|
|
1747
1806
|
<div class="__crossx-row">
|
|
1748
1807
|
<span class="__crossx-row-label">${s}</span>
|
|
1749
1808
|
<div class="__crossx-row-value">${e}</div>
|
|
1750
|
-
</div>`}function
|
|
1751
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1809
|
+
</div>`}function fo(s,e){const r=e,t=gt(s.dappName),n=s.to?`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1810
|
+
<button class="__crossx-copy-btn" data-copy="${$(s.to)}" title="Copy address">${Ae}</button>`:"<span>—</span>",i=Ps(s),o=s.data??"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
1752
1811
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1753
1812
|
<div class="__crossx-header">
|
|
1754
1813
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1759,22 +1818,22 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1759
1818
|
<div class="__crossx-body-cols">
|
|
1760
1819
|
<div class="__crossx-col-left">
|
|
1761
1820
|
<p class="__crossx-sig-subtitle">
|
|
1762
|
-
<span class="__crossx-sig-origin">${
|
|
1821
|
+
<span class="__crossx-sig-origin">${$(t)} </span>is requesting a Signature
|
|
1763
1822
|
</p>
|
|
1764
1823
|
<div class="__crossx-addr-pill">
|
|
1765
|
-
${
|
|
1766
|
-
<span class="__crossx-addr-pill-text">${
|
|
1824
|
+
${Yt}
|
|
1825
|
+
<span class="__crossx-addr-pill-text">${re(s.from)}</span>
|
|
1767
1826
|
</div>
|
|
1768
1827
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1769
1828
|
</div>
|
|
1770
1829
|
<hr class="__crossx-divider __crossx-divider--cols">
|
|
1771
1830
|
<div class="__crossx-col-right-sign">
|
|
1772
1831
|
<div class="__crossx-rows">
|
|
1773
|
-
${
|
|
1774
|
-
${
|
|
1775
|
-
${
|
|
1832
|
+
${J("To",n)}
|
|
1833
|
+
${J("Network",`<span>${Rs(s.chainId)}</span>`)}
|
|
1834
|
+
${i}
|
|
1776
1835
|
</div>
|
|
1777
|
-
<pre class="__crossx-raw-tx">${
|
|
1836
|
+
<pre class="__crossx-raw-tx">${$(o)}</pre>
|
|
1778
1837
|
</div>
|
|
1779
1838
|
</div>
|
|
1780
1839
|
<div class="__crossx-btn-row">
|
|
@@ -1783,8 +1842,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1783
1842
|
</div>
|
|
1784
1843
|
</div>
|
|
1785
1844
|
</div>
|
|
1786
|
-
`,a}function
|
|
1787
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1845
|
+
`,a}function po(s,e){const r=e,t=s.nativeSymbol??"ETH",n=s.nativeDecimals??18,i=gt(s.dappName),o=s.to?`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1846
|
+
<button class="__crossx-copy-btn" data-copy="${$(s.to)}" title="Copy address">${Ae}</button>`:"<span>—</span>",a=Ps(s),l=oo(s.value,t,n)??"—",u=document.createElement("div");return u.id=te,u.innerHTML=`
|
|
1788
1847
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1789
1848
|
<div class="__crossx-header">
|
|
1790
1849
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -1793,29 +1852,29 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1793
1852
|
<hr class="__crossx-divider">
|
|
1794
1853
|
<div class="__crossx-body">
|
|
1795
1854
|
<p class="__crossx-tx-subtitle">
|
|
1796
|
-
<span class="__crossx-sig-origin">${
|
|
1855
|
+
<span class="__crossx-sig-origin">${$(i)}</span> wants your permission to approve the following transaction.
|
|
1797
1856
|
</p>
|
|
1798
1857
|
<div class="__crossx-body-cols">
|
|
1799
1858
|
<div class="__crossx-rows">
|
|
1800
|
-
${
|
|
1801
|
-
${
|
|
1859
|
+
${J("To",o)}
|
|
1860
|
+
${J("Network",`<span>${Rs(s.chainId)}</span>`)}
|
|
1802
1861
|
${a}
|
|
1803
1862
|
</div>
|
|
1804
1863
|
<div class="__crossx-pill">
|
|
1805
|
-
<span class="__crossx-pill-from">${
|
|
1864
|
+
<span class="__crossx-pill-from">${re(s.from)}</span>
|
|
1806
1865
|
<span class="__crossx-pill-amount">${l}</span>
|
|
1807
1866
|
</div>
|
|
1808
1867
|
</div>
|
|
1809
1868
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
1810
1869
|
</div>
|
|
1811
1870
|
</div>
|
|
1812
|
-
`,u}function
|
|
1813
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1814
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1815
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1871
|
+
`,u}function gt(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function $(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function _o(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function go(s){if(typeof s=="string")return $(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return $(JSON.stringify(s))}catch{return String(s)}}function xo(s,e){const r=J("From",`<span class="__crossx-addr-text">${re(s.from)}</span>
|
|
1872
|
+
<button class="__crossx-copy-btn" data-copy="${$(s.from)}" title="Copy address">${Ae}</button>`),t=s.to?J("To",`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1873
|
+
<button class="__crossx-copy-btn" data-copy="${$(s.to)}" title="Copy address">${Ae}</button>`):"",n=s.amount?J("Transfer",`<span>${$(s.amount)}</span>`):"",i=s.fees?J("Tx Fee",`<span>${$(s.fees)}</span>`):"",o=s.txHash?J("Tx Hash",`<span class="__crossx-addr-text">${re(s.txHash)}</span>
|
|
1874
|
+
<button class="__crossx-copy-btn" data-copy="${$(s.txHash)}" title="Copy hash">${Ae}</button>`):"",a=s.total?`<div class="__crossx-total-pill">
|
|
1816
1875
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1817
|
-
<span class="__crossx-total-amount">${
|
|
1818
|
-
</div>`:"",c=document.createElement("div");return c.id=
|
|
1876
|
+
<span class="__crossx-total-amount">${$(s.total)}</span>
|
|
1877
|
+
</div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
1819
1878
|
<div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1820
1879
|
<div class="__crossx-header">
|
|
1821
1880
|
<p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
|
|
@@ -1827,14 +1886,14 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1827
1886
|
${r}
|
|
1828
1887
|
${t}
|
|
1829
1888
|
${n}
|
|
1830
|
-
${o}
|
|
1831
1889
|
${i}
|
|
1890
|
+
${o}
|
|
1832
1891
|
</div>
|
|
1833
1892
|
${a}
|
|
1834
1893
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
1835
1894
|
</div>
|
|
1836
1895
|
</div>
|
|
1837
|
-
`,c}function
|
|
1896
|
+
`,c}function mo(s,e){const r=document.createElement("div");return r.id=te,r.innerHTML=`
|
|
1838
1897
|
<div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1839
1898
|
<div class="__crossx-header">
|
|
1840
1899
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -1847,12 +1906,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1847
1906
|
</div>
|
|
1848
1907
|
</div>
|
|
1849
1908
|
</div>
|
|
1850
|
-
`,r}function
|
|
1851
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1852
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1853
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1909
|
+
`,r}function wo(s,e,r){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=s.querySelector("#__crossx-ttl"),o=s.querySelector(".__crossx-header");if(i){const w=n?ho:t?"":uo,E=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";w?(i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.innerHTML=`${w}<span>${E}</span>`):i.textContent=E}if(o&&!s.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ce,o.appendChild(w)}const a=s.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?J("From",`<span class="__crossx-addr-text">${re(e.from)}</span>
|
|
1910
|
+
<button class="__crossx-copy-btn" data-copy="${$(e.from)}" title="Copy address">${Ae}</button>`):"",l=e.to?J("To",`<span class="__crossx-addr-text">${re(e.to)}</span>
|
|
1911
|
+
<button class="__crossx-copy-btn" data-copy="${$(e.to)}" title="Copy address">${Ae}</button>`):"",u=e.amount?J("Transfer",`<span>${$(e.amount)}</span>`):"",h=e.fees?J("Tx Fee",`<span>${$(e.fees)}</span>`):"",_=e.txHash?J("Tx Hash",`<span class="__crossx-addr-text">${re(e.txHash)}</span>
|
|
1912
|
+
<button class="__crossx-copy-btn" data-copy="${$(e.txHash)}" title="Copy hash">${Ae}</button>`):"",p=e.total?`<div class="__crossx-total-pill">
|
|
1854
1913
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1855
|
-
<span class="__crossx-total-amount">${
|
|
1914
|
+
<span class="__crossx-total-amount">${$(e.total)}</span>
|
|
1856
1915
|
</div>`:"";a.innerHTML=`
|
|
1857
1916
|
<div class="__crossx-rows">
|
|
1858
1917
|
${c}
|
|
@@ -1863,7 +1922,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1863
1922
|
</div>
|
|
1864
1923
|
${p}
|
|
1865
1924
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1866
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",
|
|
1925
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",E=>{var R;E.stopPropagation();const y=w.dataset.copy;y&&((R=navigator.clipboard)==null||R.writeText(y).catch(()=>{}))})})}function yo(s,e){const r=e,t=gt(s.dappName),n=$(s.message),i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
1867
1926
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1868
1927
|
<div class="__crossx-header">
|
|
1869
1928
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1874,11 +1933,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1874
1933
|
<div class="__crossx-body-cols">
|
|
1875
1934
|
<div class="__crossx-col-left">
|
|
1876
1935
|
<p class="__crossx-sig-subtitle">
|
|
1877
|
-
<span class="__crossx-sig-origin">${
|
|
1936
|
+
<span class="__crossx-sig-origin">${$(t)} </span>is requesting a Signature
|
|
1878
1937
|
</p>
|
|
1879
1938
|
<div class="__crossx-addr-pill">
|
|
1880
|
-
${
|
|
1881
|
-
<span class="__crossx-addr-pill-text">${
|
|
1939
|
+
${Yt}
|
|
1940
|
+
<span class="__crossx-addr-pill-text">${re(s.from)}</span>
|
|
1882
1941
|
</div>
|
|
1883
1942
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1884
1943
|
</div>
|
|
@@ -1891,16 +1950,16 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1891
1950
|
</div>
|
|
1892
1951
|
</div>
|
|
1893
1952
|
</div>
|
|
1894
|
-
`,
|
|
1953
|
+
`,i}function bo(s,e){const r=e,t=gt(s.dappName);let n={};if(typeof s.typedData=="string")try{n=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(n=s.typedData);const i=n.primaryType??"—",o=n.message??{};let a=`
|
|
1895
1954
|
<div class="__crossx-td-row">
|
|
1896
1955
|
<span class="__crossx-td-label">Primary Type</span>
|
|
1897
|
-
<span class="__crossx-td-value">${
|
|
1898
|
-
</div>`;for(const[l,u]of Object.entries(
|
|
1899
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1956
|
+
<span class="__crossx-td-value">${$(i)}</span>
|
|
1957
|
+
</div>`;for(const[l,u]of Object.entries(o)){const h=go(u),p=_o(u)?`<span class="__crossx-addr-text">${re(u)}</span>
|
|
1958
|
+
<button class="__crossx-copy-btn" data-copy="${$(String(u))}" title="Copy">${Ae}</button>`:`<span>${h}</span>`;a+=`
|
|
1900
1959
|
<div class="__crossx-td-row">
|
|
1901
|
-
<span class="__crossx-td-label">${
|
|
1960
|
+
<span class="__crossx-td-label">${$(l)}</span>
|
|
1902
1961
|
<div class="__crossx-td-value">${p}</div>
|
|
1903
|
-
</div>`}const c=document.createElement("div");return c.id=
|
|
1962
|
+
</div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
1904
1963
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1905
1964
|
<div class="__crossx-header">
|
|
1906
1965
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1911,11 +1970,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1911
1970
|
<div class="__crossx-body-cols">
|
|
1912
1971
|
<div class="__crossx-col-left">
|
|
1913
1972
|
<p class="__crossx-sig-subtitle">
|
|
1914
|
-
<span class="__crossx-sig-origin">${
|
|
1973
|
+
<span class="__crossx-sig-origin">${$(t)} </span>is requesting a Signature
|
|
1915
1974
|
</p>
|
|
1916
1975
|
<div class="__crossx-addr-pill">
|
|
1917
|
-
${
|
|
1918
|
-
<span class="__crossx-addr-pill-text">${
|
|
1976
|
+
${Yt}
|
|
1977
|
+
<span class="__crossx-addr-pill-text">${re(s.from)}</span>
|
|
1919
1978
|
</div>
|
|
1920
1979
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1921
1980
|
</div>
|
|
@@ -1928,12 +1987,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1928
1987
|
</div>
|
|
1929
1988
|
</div>
|
|
1930
1989
|
</div>
|
|
1931
|
-
`,c}const
|
|
1990
|
+
`,c}const So=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1932
1991
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
1933
1992
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
1934
|
-
</svg>`;function
|
|
1935
|
-
<span class="__crossx-wallet-addr">${
|
|
1936
|
-
</button>`}).join(""),
|
|
1993
|
+
</svg>`;function vo(s,e,r){const t=r==null?void 0:r.toLowerCase(),n=s.map(o=>{const a=t&&o.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${o.index}" data-wallet-address="${$(o.address)}">
|
|
1994
|
+
<span class="__crossx-wallet-addr">${re(o.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
1995
|
+
</button>`}).join(""),i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
1937
1996
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1938
1997
|
<div class="__crossx-header">
|
|
1939
1998
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -1957,22 +2016,22 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1957
2016
|
${n}
|
|
1958
2017
|
</div>
|
|
1959
2018
|
<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
|
|
1960
|
-
<span class="__crossx-wallet-add-icon">${
|
|
2019
|
+
<span class="__crossx-wallet-add-icon">${So}</span>
|
|
1961
2020
|
<span class="__crossx-wallet-add-label">add a wallet</span>
|
|
1962
2021
|
</button>
|
|
1963
2022
|
</div>
|
|
1964
2023
|
</div>
|
|
1965
2024
|
</div>
|
|
1966
2025
|
</div>
|
|
1967
|
-
`,
|
|
2026
|
+
`,i}const Eo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1968
2027
|
<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"/>
|
|
1969
2028
|
<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"/>
|
|
1970
|
-
</svg>`,
|
|
2029
|
+
</svg>`,Io=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1971
2030
|
<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"/>
|
|
1972
2031
|
<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"/>
|
|
1973
2032
|
<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"/>
|
|
1974
2033
|
<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"/>
|
|
1975
|
-
</svg>`;function
|
|
2034
|
+
</svg>`;function Ao(s,e=!1){const r=s,t=e?`
|
|
1976
2035
|
<div class="__crossx-login-or-divider">
|
|
1977
2036
|
<hr><span>or</span><hr>
|
|
1978
2037
|
</div>
|
|
@@ -1981,7 +2040,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1981
2040
|
<span class="__crossx-connect-other-title">Connect with Other Wallets</span>
|
|
1982
2041
|
<span class="__crossx-connect-other-desc">Connect your existing Web3 wallet to manage your assets.</span>
|
|
1983
2042
|
</div>
|
|
1984
|
-
</button>`:"",n=document.createElement("div");return n.id=
|
|
2043
|
+
</button>`:"",n=document.createElement("div");return n.id=te,n.innerHTML=`
|
|
1985
2044
|
<div class="__crossx-card __crossx-card--migration" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1986
2045
|
<div class="__crossx-header">
|
|
1987
2046
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -1994,11 +2053,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1994
2053
|
<div class="__crossx-body">
|
|
1995
2054
|
<div class="__crossx-login-btn-row">
|
|
1996
2055
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
1997
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
2056
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${Eo}</span>
|
|
1998
2057
|
<span class="__crossx-login-btn-label">Sign in with Apple</span>
|
|
1999
2058
|
</button>
|
|
2000
2059
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
2001
|
-
<span class="__crossx-login-icon">${
|
|
2060
|
+
<span class="__crossx-login-icon">${Io}</span>
|
|
2002
2061
|
<span class="__crossx-login-btn-label">Sign in with Google</span>
|
|
2003
2062
|
</button>
|
|
2004
2063
|
</div>${t}
|
|
@@ -2007,7 +2066,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2007
2066
|
</p>
|
|
2008
2067
|
</div>
|
|
2009
2068
|
</div>
|
|
2010
|
-
`,n}function
|
|
2069
|
+
`,n}function To(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2011
2070
|
<div class="__crossx-card __crossx-card--migration" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2012
2071
|
<div class="__crossx-header">
|
|
2013
2072
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2021,13 +2080,13 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2021
2080
|
<p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
|
|
2022
2081
|
</div>
|
|
2023
2082
|
<button class="__crossx-recover-btn" id="__crossx-recover-btn">
|
|
2024
|
-
<span class="__crossx-recover-icon">${
|
|
2083
|
+
<span class="__crossx-recover-icon">${lo}</span>
|
|
2025
2084
|
<span class="__crossx-recover-label">Import from Social Backup</span>
|
|
2026
2085
|
</button>
|
|
2027
2086
|
${n}
|
|
2028
2087
|
</div>
|
|
2029
2088
|
</div>
|
|
2030
|
-
`,
|
|
2089
|
+
`,i}function Ro(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",h=document.createElement("div");return h.id=te,h.innerHTML=`
|
|
2031
2090
|
<div class="__crossx-card __crossx-card--migration" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2032
2091
|
<div class="__crossx-header">
|
|
2033
2092
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2047,7 +2106,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2047
2106
|
${u}
|
|
2048
2107
|
</div>
|
|
2049
2108
|
</div>
|
|
2050
|
-
`,h}function
|
|
2109
|
+
`,h}function Po(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function Oo(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?Po(i):null,a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
2051
2110
|
<div class="__crossx-card __crossx-card--migration" style="${ue(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2052
2111
|
<div class="__crossx-header">
|
|
2053
2112
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2063,19 +2122,19 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2063
2122
|
</div>
|
|
2064
2123
|
<div class="__crossx-pin-lock-messages">
|
|
2065
2124
|
<p class="__crossx-pin-lock-message">${n?r:"Please try again after the lock expires."}</p>
|
|
2066
|
-
${
|
|
2125
|
+
${o?`<p class="__crossx-pin-lock-secondary">(Available from ${o})</p>`:""}
|
|
2067
2126
|
</div>
|
|
2068
2127
|
</div>
|
|
2069
2128
|
</div>
|
|
2070
|
-
`,{overlay:a,startCountdown:l=>{if(n||!
|
|
2129
|
+
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const h=setInterval(()=>{Date.now()>=i&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function Co(s){const r=[s.check1,s.check2].map((t,n)=>`
|
|
2071
2130
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2072
|
-
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${
|
|
2073
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
2131
|
+
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Lo}</div>
|
|
2132
|
+
<span class="__crossx-pw-notice-item-text">${$(t)}</span>
|
|
2074
2133
|
</div>
|
|
2075
2134
|
`).join("");return`
|
|
2076
2135
|
<div class="__crossx-header">
|
|
2077
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2078
|
-
<p class="__crossx-pw-subtitle">${
|
|
2136
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${$(s.title)}</p>
|
|
2137
|
+
<p class="__crossx-pw-subtitle">${$(s.headerSubtitle)}</p>
|
|
2079
2138
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
2080
2139
|
</div>
|
|
2081
2140
|
<hr class="__crossx-divider">
|
|
@@ -2083,28 +2142,28 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2083
2142
|
<div class="__crossx-pw-fields __crossx-pw-fields--notice">
|
|
2084
2143
|
<div class="__crossx-pw-notice-header">
|
|
2085
2144
|
<div class="__crossx-pw-notice-title-row">
|
|
2086
|
-
<span class="__crossx-pw-notice-icon">${
|
|
2087
|
-
<p class="__crossx-pw-notice-title">${
|
|
2145
|
+
<span class="__crossx-pw-notice-icon">${Do}</span>
|
|
2146
|
+
<p class="__crossx-pw-notice-title">${$(s.noticeTitle)}</p>
|
|
2088
2147
|
</div>
|
|
2089
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2148
|
+
<p class="__crossx-pw-notice-desc">${$(s.noticeDesc)}</p>
|
|
2090
2149
|
</div>
|
|
2091
2150
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2092
2151
|
${r}
|
|
2093
2152
|
</div>
|
|
2094
2153
|
</div>
|
|
2095
2154
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2096
|
-
data-next-label="${
|
|
2097
|
-
data-submit-label="${
|
|
2098
|
-
${
|
|
2155
|
+
data-next-label="${$(s.nextButton)}"
|
|
2156
|
+
data-submit-label="${$(s.submitButton)}">
|
|
2157
|
+
${$(s.nextButton)}
|
|
2099
2158
|
</button>
|
|
2100
2159
|
</div>
|
|
2101
2160
|
<div class="__crossx-home-indicator"></div>
|
|
2102
|
-
`}function
|
|
2103
|
-
${
|
|
2161
|
+
`}function jt(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${$(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${$(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${$(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2162
|
+
${Cs}
|
|
2104
2163
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2105
|
-
</p>`:"",a=e?" --locked":"",
|
|
2164
|
+
</p>`:"",a=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',c=e?" --locked":"",l=Array.from({length:6},(u,h)=>`<input class="__crossx-pin6-box${c}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${h+1}"${e?" disabled":""}>`).join("");return`
|
|
2106
2165
|
<div class="__crossx-header">
|
|
2107
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2166
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${$(s.title)}</p>
|
|
2108
2167
|
${t}
|
|
2109
2168
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
2110
2169
|
</div>
|
|
@@ -2112,20 +2171,21 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2112
2171
|
<div class="__crossx-pin6-body"${r}>
|
|
2113
2172
|
${n}
|
|
2114
2173
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
2115
|
-
${
|
|
2174
|
+
${l}
|
|
2116
2175
|
</div>
|
|
2117
|
-
${o}
|
|
2118
2176
|
${i}
|
|
2177
|
+
${a}
|
|
2178
|
+
${o}
|
|
2119
2179
|
</div>
|
|
2120
2180
|
<div class="__crossx-home-indicator"></div>
|
|
2121
|
-
`}function
|
|
2181
|
+
`}function Os(s,e){const r=document.createElement("div");return r.id=te,r.innerHTML=`
|
|
2122
2182
|
<div class="__crossx-card __crossx-card--pin6" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2123
2183
|
${e}
|
|
2124
2184
|
</div>
|
|
2125
|
-
`,r}function
|
|
2185
|
+
`,r}function ko(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function No(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function Xt(s,e,r,t,n,i){var H,z;let o=!!(i&&i>Date.now()),a=!1;const c=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),l=()=>s.querySelector("#__crossx-pin6-boxes"),u=()=>s.querySelector("#__crossx-pin6-error"),h=()=>s.querySelector("#__crossx-pin6-lock-msg"),_=()=>s.querySelector("#__crossx-pin6-lock-countdown"),p=()=>s.querySelector(".__crossx-pin6-body"),w=()=>c().map(P=>P.value).join(""),E=P=>{o=P,c().forEach(b=>{b.disabled=P,b.classList.toggle("--locked",P)})},y=()=>s.querySelector("#__crossx-pin6-attempt"),R=()=>{const P=u();P&&(P.textContent="")},N=(P,b)=>{var I;let S=y();if(!S){S=document.createElement("p"),S.className="__crossx-pin6-attempt",S.id="__crossx-pin6-attempt";const x=u();x?x.insertAdjacentElement("afterend",S):(I=p())==null||I.appendChild(S)}S.textContent=`${P}/${b}`},B=()=>{const P=y();P&&(P.textContent="")},M=P=>{const b=u();b&&(b.textContent=P);const S=l();S==null||S.classList.add("--shake"),setTimeout(()=>S==null?void 0:S.classList.remove("--shake"),500),c().forEach(I=>{I.value=""}),setTimeout(()=>{var I;return(I=c()[0])==null?void 0:I.focus()},50)},V=P=>{var m;E(!0),c().forEach(v=>{v.value=""});const b=u();if(b&&(b.textContent="Too many failed attempts. Please wait."),!h()){const v=document.createElement("p");v.className="__crossx-pin6-lock-msg",v.id="__crossx-pin6-lock-msg",v.innerHTML=`${Cs}<span id="__crossx-pin6-lock-countdown"></span>`;const A=u();A?A.insertAdjacentElement("afterend",v):(m=p())==null||m.appendChild(v)}const S=()=>{var k;const v=P-Date.now(),A=_();v<=0?(clearInterval(I),E(!1),(k=h())==null||k.remove(),b&&(b.textContent=""),setTimeout(()=>{var C;return(C=c()[0])==null?void 0:C.focus()},50)):A&&(A.textContent=` ${No(v)}`)},I=setInterval(S,1e3);S();const x=new MutationObserver(()=>{document.contains(s)||(clearInterval(I),x.disconnect())});x.observe(document.body,{childList:!0,subtree:!1})},F=async()=>{if(o||a)return;const P=w();if(P.length===6){a=!0,c().forEach(b=>{b.disabled=!0});try{if(n){const b=await n(P);b.ok?e(P):b.lockExpiresAt?(B(),V(b.lockExpiresAt)):(M(b.error??"Incorrect PIN. Please try again."),b.attemptCount!=null&&b.maxAttempts!=null?N(b.attemptCount,b.maxAttempts):B())}else e(P)}catch(b){t&&t(b)}finally{a=!1,o||c().forEach(b=>{b.disabled=!1})}}};i&&i>Date.now()?V(i):setTimeout(()=>{var P;return(P=c()[0])==null?void 0:P.focus()},100);const ne=()=>{if(o||a)return;const P=c(),b=P.find(S=>!S.value)??P[P.length-1];b==null||b.focus()};(H=l())==null||H.addEventListener("click",P=>{P.target.classList.contains("__crossx-pin6-box")||ne()}),(z=p())==null||z.addEventListener("click",P=>{const b=P.target;b.classList.contains("__crossx-pin6-box")||b.closest("button")||ne()}),c().forEach((P,b)=>{P.addEventListener("input",()=>{var I;const S=P.value.replace(/\D/g,"").slice(-1);P.value=S,R(),S&&b<5&&((I=c()[b+1])==null||I.focus()),w().length===6&&setTimeout(F,80)}),P.addEventListener("keydown",S=>{var I,x;if(S.key==="Backspace"){if(S.preventDefault(),P.value)P.value="";else if(b>0){const m=c()[b-1];m.value="",m.focus()}}else S.key==="ArrowLeft"&&b>0?(S.preventDefault(),(I=c()[b-1])==null||I.focus()):S.key==="ArrowRight"&&b<5?(S.preventDefault(),(x=c()[b+1])==null||x.focus()):S.key==="Escape"&&r()}),P.addEventListener("paste",S=>{var m,v;S.preventDefault();const I=(((m=S.clipboardData)==null?void 0:m.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!I)return;const x=c();I.split("").forEach((A,k)=>{x[k]&&(x[k].value=A)}),(v=x[Math.min(I.length-1,5)])==null||v.focus(),R(),w().length===6&&setTimeout(F,80)}),P.addEventListener("focus",()=>P.select())})}const Cs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2126
2186
|
<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"/>
|
|
2127
|
-
</svg>`,
|
|
2187
|
+
</svg>`,Lo=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2128
2188
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2129
|
-
</svg>`,
|
|
2189
|
+
</svg>`,Do=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2130
2190
|
<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"/>
|
|
2131
|
-
</svg>`;function Li(s,e,r){var o;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var h;c.preventDefault();const l=(((h=c.clipboardData)==null?void 0:h.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,p)=>{t[p]&&(t[p].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class Di{constructor(e="light",r){this.theme=e,this.overrides=r,this.tokens=Es(e,r)}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=Es(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise(n=>{var b;we();const o=[...e],i=bi(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",ye(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},u=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const A=y.dataset.walletAddress??"",N=parseInt(y.dataset.walletIndex??"0",10);u({address:A,index:N})})})})();const p=i.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const y=await r();o.push(y);const A=i.querySelector("#__crossx-wallet-list");if(A){const N=document.createElement("button");N.className="__crossx-wallet-item",N.dataset.walletIndex=String(y.index),N.dataset.walletAddress=y.address,N.innerHTML=`<span class="__crossx-wallet-addr">${se(y.address)}</span>`,N.addEventListener("click",()=>u(y)),A.appendChild(N),N.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(b=i.querySelector("#__crossx-close-btn"))==null||b.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(e){return new Promise(r=>{var c,l,u,h;we();const t=Ei(this.tokens,e==null?void 0:e.showConnectOtherWallets);ye(t);const n=()=>t.remove(),o=_=>{n(),r(_)},i=()=>{n(),r(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>o("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>o("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>o("external")),(h=t.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",i),t.addEventListener("click",_=>{_.target===t&&i()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(_=>{_.addEventListener("click",p=>p.stopPropagation())});const a=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;we();const n=Ii(this.tokens,r);ye(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),r){const u=()=>{o(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const h=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)}})}showPinSetupPrompt(e){return new Promise(r=>{we();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=Rs(this.tokens,Pi(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",ye(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=N=>{u(),r(N)},_=()=>{u(),r(null)},p=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."},b=N=>{var K;p.innerHTML=Yt({title:i.title,headerSubtitle:i.headerSubtitle}),(K=p.querySelector("#__crossx-close-btn"))==null||K.addEventListener("click",_),jt(p,W=>{W===N?h(N):y(o.mismatchError)},_)},y=N=>{var K;p.innerHTML=Yt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:N}),(K=p.querySelector("#__crossx-close-btn"))==null||K.addEventListener("click",_),jt(p,W=>{const Y=Oi(W,w);Y?y(Y):b(W)},_)};(()=>{var F;const N=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),K=p.querySelector("#__crossx-pin-notice-next"),W=new Set;K.removeAttribute("disabled");const Y=K.dataset.nextLabel??"Next",G=K.dataset.submitLabel??"I Understand",O=()=>{const C=W.size===N.length;K.classList.toggle("--disabled",!C),K.textContent=C?G:Y},v=(C,T)=>{if(W.has(T))return;const I=C.querySelector(`#__crossx-notice-check-${T}`);W.add(T),I.classList.add("--checked"),C.setAttribute("aria-checked","true"),O()},L=(C,T)=>{if(!W.has(T))return;const I=C.querySelector(`#__crossx-notice-check-${T}`);W.delete(T),I.classList.remove("--checked"),C.setAttribute("aria-checked","false"),O()};N.forEach(C=>{const T=parseInt(C.dataset.checkIndex??"0",10);C.addEventListener("click",()=>{W.has(T)?L(C,T):v(C,T)}),C.addEventListener("keydown",I=>{(I.key===" "||I.key==="Enter")&&(I.preventDefault(),W.has(T)?L(C,T):v(C,T))})}),K.addEventListener("click",()=>{if(W.size===N.length){y(e==null?void 0:e.errorMessage);return}const C=N.find(I=>{const g=parseInt(I.dataset.checkIndex??"0",10);return!W.has(g)});if(!C)return;const T=parseInt(C.dataset.checkIndex??"0",10);C.scrollIntoView({behavior:"smooth",block:"nearest"}),C.classList.add("--highlight"),setTimeout(()=>{C.classList.remove("--highlight"),v(C,T)},400)}),(F=p.querySelector("#__crossx-close-btn"))==null||F.addEventListener("click",_)})(),a.addEventListener("click",N=>{N.target===a&&_()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var y;we();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=Rs(this.tokens,Yt({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",ye(c);let u=!1;const h=()=>{u||(u=!0,c.remove(),document.body.style.overflow=l)},_=A=>{h(),r(A)},p=()=>{h(),r(null)},w=A=>{h(),t(A)},b=c.querySelector(".__crossx-card");(y=b.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",p),jt(b,_,p,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",A=>{A.target===c&&p()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var a;we();const t=Ai(this.tokens,e);ye(t);const n=()=>t.remove(),o=c=>{n(),r(c)},i=()=>{n(),r(null)};Li(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;we();const{overlay:n,startCountdown:o}=Ri(this.tokens,e,r);ye(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;we();const t=_i(e,this.tokens);ye(t);const n=()=>t.remove(),o=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const h=l.dataset.copy;h&&((_=navigator.clipboard)==null||_.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,r){return new Promise(t=>{we();const n=gi(e,this.tokens);ye(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,h;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{i||(xi(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(r=>{var c,l,u;we();let t;e.type==="sign-message"?t=mi(e,this.tokens):e.type==="sign-typed-data"?t=wi(e,this.tokens):e.type==="sign"?t=ui(e,this.tokens):t=hi(e,this.tokens),ye(t);const n=()=>t.remove(),o=()=>{n(),r(!0)},i=()=>{n(),r(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",_=>{var w;_.stopPropagation();const p=h.dataset.copy;p&&((w=navigator.clipboard)==null||w.writeText(p).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 Os{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Mi(s,e){s.debug;const r=et.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},o=t.authMode!=="cookie"&&cr.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new cr(s.projectId):new Qs,a=new jo,c=new ei,l=new De,u=new Os,h=new wt;let _;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new ri(i,h)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new je(n,i,c,u,h));const p=new Xe(n,c),w=new Di(s.theme??"light",s.themeTokens),b=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w,y=new tt(t,n,i,a,c,l,_,u,b,p,h);return typeof window<"u"&&(window.__crossxSDK=y),y}function $i(s){const e=Wi(s),r=Ui(e),t=JSON.parse(r);Bi(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Wi(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function Ui(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=Hi(s);return decodeURIComponent(e)}function Hi(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Bi(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return Z.CROSSxError=m,Z.CROSSxEthereumProvider=Xt,Z.CROSSxSDK=tt,Z.ChainId=Ls,Z.ErrorCode=f,Z.PinMemoryStore=wt,Z.TokenMemoryStore=Os,Z.createCROSSxSDK=Mi,Z.parseOAuthDeeplink=$i,Object.defineProperty(Z,Symbol.toStringTag,{value:"Module"}),Z}({});
|
|
2191
|
+
</svg>`;function Mo(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var h;c.preventDefault();const l=(((h=c.clipboardData)==null?void 0:h.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,p)=>{t[p]&&(t[p].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class $o{constructor(e="light",r){this.theme=e,this.overrides=r,this.tokens=As(e,r)}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=As(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise(n=>{var E;we();const i=[...e],o=vo(i,this.tokens,t),a=Jt();ye(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},u=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const R=y.dataset.walletAddress??"",N=parseInt(y.dataset.walletIndex??"0",10);u({address:R,index:N})})})})();const p=o.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const y=await r();i.push(y);const R=o.querySelector("#__crossx-wallet-list");if(R){const N=document.createElement("button");N.className="__crossx-wallet-item",N.dataset.walletIndex=String(y.index),N.dataset.walletAddress=y.address,N.innerHTML=`<span class="__crossx-wallet-addr">${re(y.address)}</span>`,N.addEventListener("click",()=>u(y)),R.appendChild(N),N.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(E=o.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",h),o.addEventListener("click",y=>{y.target===o&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(e){return new Promise(r=>{var c,l,u,h;we();const t=Ao(this.tokens,e==null?void 0:e.showConnectOtherWallets);ye(t);const n=()=>t.remove(),i=_=>{n(),r(_)},o=()=>{n(),r(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>i("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>i("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>i("external")),(h=t.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",o),t.addEventListener("click",_=>{_.target===t&&o()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(_=>{_.addEventListener("click",p=>p.stopPropagation())});const a=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;we();const n=To(this.tokens,r);ye(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const h=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)}})}showPinSetupPrompt(e){return new Promise(r=>{we();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},i={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=Os(this.tokens,Co(n)),c=Jt();ye(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},h=N=>{u(),r(N)},_=()=>{u(),r(null)},p=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."},E=N=>{var B;p.innerHTML=jt({title:o.title,headerSubtitle:o.headerSubtitle}),(B=p.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",_),Xt(p,M=>{M===N?h(N):y(i.mismatchError)},_)},y=N=>{var B;p.innerHTML=jt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:N}),(B=p.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",_),Xt(p,M=>{const V=ko(M,w);V?y(V):E(M)},_)};(()=>{var P;const N=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),B=p.querySelector("#__crossx-pin-notice-next"),M=new Set;B.removeAttribute("disabled");const V=B.dataset.nextLabel??"Next",F=B.dataset.submitLabel??"I Understand",ne=()=>{const b=M.size===N.length;B.classList.toggle("--disabled",!b),B.textContent=b?F:V},H=(b,S)=>{if(M.has(S))return;const I=b.querySelector(`#__crossx-notice-check-${S}`);M.add(S),I.classList.add("--checked"),b.setAttribute("aria-checked","true"),ne()},z=(b,S)=>{if(!M.has(S))return;const I=b.querySelector(`#__crossx-notice-check-${S}`);M.delete(S),I.classList.remove("--checked"),b.setAttribute("aria-checked","false"),ne()};N.forEach(b=>{const S=parseInt(b.dataset.checkIndex??"0",10);b.addEventListener("click",()=>{M.has(S)?z(b,S):H(b,S)}),b.addEventListener("keydown",I=>{(I.key===" "||I.key==="Enter")&&(I.preventDefault(),M.has(S)?z(b,S):H(b,S))})}),B.addEventListener("click",()=>{if(M.size===N.length){y(e==null?void 0:e.errorMessage);return}const b=N.find(I=>{const x=parseInt(I.dataset.checkIndex??"0",10);return!M.has(x)});if(!b)return;const S=parseInt(b.dataset.checkIndex??"0",10);b.scrollIntoView({behavior:"smooth",block:"nearest"}),b.classList.add("--highlight"),setTimeout(()=>{b.classList.remove("--highlight"),H(b,S)},400)}),(P=p.querySelector("#__crossx-close-btn"))==null||P.addEventListener("click",_)})(),a.addEventListener("click",N=>{N.target===a&&_()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var y;we();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=Os(this.tokens,jt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),l=Jt();ye(c);let u=!1;const h=()=>{u||(u=!0,c.remove(),l())},_=R=>{h(),r(R)},p=()=>{h(),r(null)},w=R=>{h(),t(R)},E=c.querySelector(".__crossx-card");(y=E.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",p),Xt(E,_,p,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",R=>{R.target===c&&p()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var a;we();const t=Ro(this.tokens,e);ye(t);const n=()=>t.remove(),i=c=>{n(),r(c)},o=()=>{n(),r(null)};Mo(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;we();const{overlay:n,startCountdown:i}=Oo(this.tokens,e,r);ye(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;we();const t=xo(e,this.tokens);ye(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const h=l.dataset.copy;h&&((_=navigator.clipboard)==null||_.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{we();const n=mo(e,this.tokens);ye(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,h;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(wo(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(r=>{var c,l,u;we();let t;e.type==="sign-message"?t=yo(e,this.tokens):e.type==="sign-typed-data"?t=bo(e,this.tokens):e.type==="sign"?t=fo(e,this.tokens):t=po(e,this.tokens),ye(t);const n=()=>t.remove(),i=()=>{n(),r(!0)},o=()=>{n(),r(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",i),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",_=>{var w;_.stopPropagation();const p=h.dataset.copy;p&&((w=navigator.clipboard)==null||w.writeText(p).catch(()=>{}))})}),t.addEventListener("click",h=>{h.target===t&&o()});const a=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}}class ks{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Wo(s,e){s.debug;const r=tt.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&dr.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new dr(s.projectId):new en,a=new ji,c=new eo,l=new Me,u=new ks,h=new wt;let _;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new ro(o,h)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new Je(n,o,c,u,h));const p=new Ze(n,c),w=new $o(s.theme??"light",s.themeTokens),E=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w,y=new rt(t,n,o,a,c,l,_,u,E,p,h);return typeof window<"u"&&(window.__crossxSDK=y),y}function Uo(s){const e=Ho(s),r=Bo(e),t=JSON.parse(r);Ko(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Ho(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function Bo(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=Fo(s);return decodeURIComponent(e)}function Fo(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Ko(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return X.CROSSxError=g,X.CROSSxEthereumProvider=Zt,X.CROSSxSDK=rt,X.ChainId=Ms,X.ErrorCode=f,X.PinMemoryStore=wt,X.TokenMemoryStore=ks,X.createCROSSxSDK=Wo,X.parseOAuthDeeplink=Uo,Object.defineProperty(X,Symbol.toStringTag,{value:"Module"}),X}({});
|