@nexus-cross/crossx-sdk-core 1.5.1 → 2.0.1-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts +5 -5
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/core/ports/ConfirmationPort.d.ts +5 -5
- package/dist/core/ports/ConfirmationPort.d.ts.map +1 -1
- package/dist/core/types/connectOtherWallet.d.ts +17 -0
- package/dist/core/types/connectOtherWallet.d.ts.map +1 -0
- package/dist/core/types/events.d.ts +5 -1
- package/dist/core/types/events.d.ts.map +1 -1
- package/dist/core/types/index.d.ts +24 -15
- package/dist/core/types/index.d.ts.map +1 -1
- package/dist/core/utils/resolveConnectOtherWallets.d.ts +15 -0
- package/dist/core/utils/resolveConnectOtherWallets.d.ts.map +1 -0
- package/dist/crossx.global +158 -123
- package/dist/index.cjs +152 -117
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1188 -1100
- package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/crossx.global
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var CROSSx=function(
|
|
1
|
+
var CROSSx=function(z){"use strict";var ia=Object.defineProperty;var oa=(z,h,g)=>h in z?ia(z,h,{enumerable:!0,configurable:!0,writable:!0,value:g}):z[h]=g;var P=(z,h,g)=>oa(z,typeof h!="symbol"?h+"":h,g);var bt,Ur;var h=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",r.SESSION_EXPIRED="SESSION_EXPIRED",r.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.BROADCAST_FAILED="BROADCAST_FAILED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",r.PIN_CANCELLED="PIN_CANCELLED",r.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",r.PIN_LOCKED="PIN_LOCKED",r.HMAC_REQUIRED="HMAC_REQUIRED",r.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",r.WITHDRAW_FAILED="WITHDRAW_FAILED",r.USER_NOT_FOUND="USER_NOT_FOUND",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(h||{});class g extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,g.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}var We=(r=>(r.MetaMask="io.metamask",r.Binance="com.binance.wallet",r.CROSSx="crossx",r))(We||{});const Fr={"io.metamask":"MetaMask","com.binance.wallet":"Binance Wallet",crossx:"CROSSx"},ss=["crossx","io.metamask","com.binance.wallet"];function rs(r){return Fr[r]??r}function Kr(r){return Array.isArray(r.connectOtherWallets)&&r.connectOtherWallets.length>0?[...r.connectOtherWallets]:r.showConnectOtherWallets===!0?[...ss]:[]}const rt={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}},Gr=Object.fromEntries(Object.entries(rt).map(([r,e])=>[r,e.caipId])),qr=new Map(Object.values(rt).map(r=>[r.caipId,r]));new Map(Object.values(rt).map(r=>[r.chainId,r]));const Jr={symbol:"",decimals:18};function St(r){var e;return((e=qr.get(r))==null?void 0:e.nativeCurrency)??Jr}class ns{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new g(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new g(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let be=null;function aa(r){}function is(r){be=r}const u={info(...r){if(be){be.log(...r);return}console.log(...r)},log(...r){if(be){be.log(...r);return}},warn(...r){if(be){be.warn(...r);return}},error(...r){if(be){be.error(...r);return}}},Vr={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",pinLocked_failureWarning:"추가 실패 시 계정이 잠금됩니다.",pinLocked_permanent:"너무 많은 시도 실패로 계정이 영구 잠금되었습니다.",alert_sessionExpired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_accountWithdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_walletNotFound:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_differentAccount:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
2
2
|
|
|
3
|
-
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},
|
|
3
|
+
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_appleAccount:"Apple 계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},os={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Please sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_walletNotFound:"Wallet data could not be found. Please sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
|
|
4
4
|
|
|
5
|
-
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},Kr={ko:Fr,en:rs};function Se(r="en",e){return Kr[r]??rs}const ns="crossx_access_token",is="crossx_refresh_token",os="crossx_user_info",wt=class wt{constructor(e,s,t,n,i,o,a){this.config=e,this.storage=s,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"}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new g(p.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new g(p.OAUTH_POPUP_BLOCKED,i):new g(p.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:_}=await this.exchangeFirebaseToken(e,u);let h,x,v;try{const T=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(T).join(", ")),x=(i=T.firebase)==null?void 0:i.sign_in_provider;const k=((o=T.firebase)==null?void 0:o.identities)??{};v=T.email??((a=k.email)==null?void 0:a[0]),x==="google.com"?h=(c=k["google.com"])==null?void 0:c[0]:x==="apple.com"&&(h=(l=k["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!h,"email:",v??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const T=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",T.sub,"exp:",T.exp,"필드:",Object.keys(T).join(", "));const k=await this.crypto.verifyJWT(f);if(n=k.signatureVerified??!1,!k.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const B=k.payload,$=B.email??v??s;d.log("[CROSSx] email 소스 — CROSSx JWT:",B.email??"(없음)","/ Firebase JWT:",v??"(없음)","/ OAuth 콜백:",s??"(없음)","→",$??"(없음)"),t={id:B.sub,email:$,signInProvider:x,providerSub:h},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const T=this.crypto.decodeJWT(e);t={id:T.sub,email:T.email??s,signInProvider:x,providerSub:h},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const E=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,E),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)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 s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof g&&e.code===p.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=wt.REFRESH_RELOGIN_CODES.has(c.code);throw new g(u?p.SESSION_EXPIRED:p.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new g(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof g&&e.code===p.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(os);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(ns);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(is);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(os),await this.storage.remove(ns),await this.storage.remove(is),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof g&&i.code===p.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(i.code===p.PROJECT_NOT_REGISTERED||i.code===p.PROJECT_ID_MISSING||i.code===p.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};wt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let St=wt;class Gr{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class qr{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new g(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class vt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Jr{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new g(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Vr{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}var rt={environment:"production"};const We={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function zr(r){const e=r.environment;return e&&e in We?We[e]:null}function Yr(){try{if(typeof rt<"u"){const r=typeof rt=="string"?JSON.parse(rt):rt,e=zr(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in We)return We[r]}catch{}return We.production}const jr=2e3,as=6e4,Xr=1e3,Zr=1e4,Qr="0x77359400",cs="0x3B9ACA00",ls=130,ds=6,us=18,hs=3e4,en=5*60*1e3,tn=30*1e3;function Ye(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Z=class Z extends Vr{constructor(e,s,t,n,i,o,a,c,l,u,f){var _,h;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=s,e.logger&&ss(e.logger),this.confirmation=l,this.pinStore=f??new vt,this.chainRegistry=u,this.jsonRpc=new Jr(u,i),this.signInUseCase=new St(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Gr(this.internalConfig,t,c),this.migrateWalletUseCase=new qr(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(h=a.setTokenRefresher)==null||h.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var s,t;d.log("[CROSSx SDK] v1.5.1 초기화 중..."),this.confirmation.setMessages(Se(this._config.locale));try{const n=Yr();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=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===p.PIN_CANCELLED))throw o;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.5.1 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??null}catch(n){throw new g(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=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(p.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...s,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}catch(t){throw t instanceof g&&t.code===p.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(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw new g(p.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new g(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new g(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new g(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof g&&s.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof g?s:new g(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.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(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.ensurePinForSigning();const n=s.length,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.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(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof g?s:new g(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Se(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new g(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof g&&s.code===p.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(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof g&&s.code===p.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(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(p.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:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,o.signature,n.address),{chainId:e,signature:o.signature,message:s,address:n.address}}catch(o){throw o instanceof g?o:new g(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Z.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(p.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:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return Z.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof g?o:new g(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,s){return this.signTypedData(Z.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=bt(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(p.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 Z.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(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=bt(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(p.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(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??Xr,i=Zr,o=t.timeoutMs??as,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new g(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var v,E;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??jr,l=i??((E=this._config.receiptPolling)==null?void 0:E.timeoutMs)??as,u=bt(e),f=s.from??"";let _,h;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(T=>{_=T;const k=BigInt(T.gasUsed)*BigInt(T.effectiveGasPrice),B=s.value?BigInt(s.value):0n,$=Z.formatTxAmount(s.value,u.symbol,u.decimals),J=Z.formatTxAmount("0x"+k.toString(16),u.symbol,u.decimals),G=Z.formatTxAmount("0x"+(B+k).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:T.from,to:T.to??s.to,amount:$,fees:J,total:G,nativeSymbol:u.symbol,status:T.status==="0x1"?"success":"reverted"}}).catch(T=>(h=T instanceof Error?T:new Error(String(T)),{chainId:e,txHash:a,from:f,to:s.to,amount:Z.formatTxAmount(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:s.to},x),h)throw h;return{chainId:e,txHash:a,receipt:_}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(p.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(p.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(p.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(p.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(p.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(p.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:Z.formatWei(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(p.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(us),n=s/t,o=(s%t).toString().padStart(us,"0").replace(/0+$/,"").slice(0,ds);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new ts(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(p.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,s,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,ds).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${s}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(f===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const _=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,f,e));if(!_){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(_.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const h=_.pinStatus;if(o=h.maxAttempts,i=o-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const x=h.lockExpiresAt*1e3,v=Math.max(1,Math.round((x-Date.now())/1e3)),E=v<=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 잠금 — ${v}초, 메시지: ${E}`),await this.confirmation.showRecoveryPinLockedPrompt(v,E),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===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const h=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:h.sessionAlert_title,message:h.alert_sessionExpired,email:this.userEmail?Ye(this.userEmail,h.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.clearAuthState(),_}if(_.code===p.MIGRATION_PIN_LOCKED){const h=_.details;if(o=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.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 x=((h==null?void 0:h.lockExpiresAt)??0)*1e3,v=Math.max(1,Math.round((x-Date.now())/1e3)),E=v<=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 이미 잠금 — ${v}초`),await this.confirmation.showRecoveryPinLockedPrompt(v,E),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 f=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof g&&f.code===p.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof g&&f.code===p.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:_.sessionAlert_title,message:_.alert_sessionExpired,email:this.userEmail?Ye(this.userEmail,_.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const v=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",v.address),v}catch(v){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",v),v}}throw this.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,s){const t=h=>!(h!=null&&h.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,f,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,i?this.estimateGas(e,s):null,o?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const h=_;if(h){const x=cs;c.maxFeePerGas="0x"+(BigInt(h)+BigInt(x)).toString(16),c.maxPriorityFeePerGas=x,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",h,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Qr,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=cs,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=Z.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new g(p.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(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new g(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==ls)throw new g(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${ls} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new g(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(p.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 s,t,n,i;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=Z.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/-10033)"),this.clearAuthState())}async signInAgain(){var n,i;this.ensureInitialized();const e=this.providerSub,s=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(f){throw this.clearAuthState(),f}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:s?!!l&&s===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=Se(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?Ye(this.userEmail,f.sessionAlert_appleAccount):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(s){const t=Se(this._config.locale??"en"),n=this.userEmail?Ye(this.userEmail,t.sessionAlert_appleAccount):void 0;if(s instanceof g&&s.code===p.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(s instanceof g&&s.code===p.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(!(s instanceof g)||s.code!==p.SESSION_EXPIRED)throw s;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new g(p.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new g(p.SESSION_EXPIRED,o.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(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=Se(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new g(p.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:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.pinStore.clear(),u instanceof g){if(u.code===p.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===p.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===p.PIN_LOCKED)return Z.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new g(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof g&&(c.code===p.AUTH_NOT_AUTHENTICATED||c.code===p.AUTH_TOKEN_EXPIRED||c.code===p.SESSION_EXPIRED)&&c.code!==p.SESSION_EXPIRED){const l=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?Ye(this.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this._verifyPinMutex=null}}static parsePinError(e,s){if(e.code===p.PIN_WRONG)return{errorMessage:s.pinInput_error};if(e.code===p.PIN_INVALID)return{errorMessage:e.message};if(e.code===p.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,s){const t=Z.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="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 s=Se(this._config.locale??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Z.parsePinError(n,s),!t)throw n}else throw n}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof g&&(t=Z.parsePinError(n,s),t))continue;throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new g(p.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new g(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new g(p.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(),ss(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Z.OFFCHAIN_CHAIN_ID="0";let nt=Z;class sn{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return d.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw d.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Et="crossx-sdk",rn=1,ge="data",Ne="keys",it="aes-primary",nn=12;class ps{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,rn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ge)||i.createObjectStore(ge),i.objectStoreNames.contains(Ne)||i.createObjectStore(Ne)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,it);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,it,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Et)return null;try{const e=await this.openDB(Et),s=e.transaction([Ne,ge],"readonly"),t=s.objectStore(Ne).get(it),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=s.objectStore(ge).getAll(),o=s.objectStore(ge).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ne,it,n);for(let l=0;l<c.length;l++)await this.idbPut(ge,String(c[l]),a[l]);return indexedDB.deleteDatabase(Et),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(nn);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(ge,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(ge,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return d.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ge,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ge)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const At=crypto,fs=r=>r instanceof CryptoKey,ot=new TextEncoder,je=new TextDecoder;function on(...r){const e=r.reduce((n,{length:i})=>n+i,0),s=new Uint8Array(e);let t=0;for(const n of r)s.set(n,t),t+=n.length;return s}const an=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},Re=r=>{let e=r;e instanceof Uint8Array&&(e=je.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return an(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class ee extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}ee.code="ERR_JOSE_GENERIC";class he extends ee{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class It extends ee{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}It.code="ERR_JWT_EXPIRED";class _s extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}_s.code="ERR_JOSE_ALG_NOT_ALLOWED";class xe extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}xe.code="ERR_JOSE_NOT_SUPPORTED";class cn extends ee{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}cn.code="ERR_JWE_DECRYPTION_FAILED";class ln extends ee{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ln.code="ERR_JWE_INVALID";class X extends ee{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}X.code="ERR_JWS_INVALID";class me extends ee{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}me.code="ERR_JWT_INVALID";class dn extends ee{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}dn.code="ERR_JWK_INVALID";class Tt extends ee{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Tt.code="ERR_JWKS_INVALID";class Rt extends ee{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Rt.code="ERR_JWKS_NO_MATCHING_KEY";class gs extends ee{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}gs.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class xs extends ee{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}xs.code="ERR_JWKS_TIMEOUT";class ms extends ee{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}ms.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Xe(r,e){return r.name===e}function kt(r){return parseInt(r.name.slice(4),10)}function un(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hn(r,e){if(e.length&&!e.some(s=>r.usages.includes(s))){let s="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();s+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?s+=`one of ${e[0]} or ${e[1]}.`:s+=`${e[0]}.`;throw new TypeError(s)}}function pn(r,e,...s){switch(e){case"HS256":case"HS384":case"HS512":{if(!Xe(r.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(kt(r.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Xe(r.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(kt(r.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Xe(r.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(kt(r.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!Xe(r.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Xe(r.algorithm,"ECDSA"))throw we("ECDSA");const t=un(e);if(r.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hn(r,s)}function ws(r,e,...s){var t;if(s=s.filter(Boolean),s.length>2){const n=s.pop();r+=`one of type ${s.join(", ")}, or ${n}.`}else s.length===2?r+=`one of type ${s[0]} or ${s[1]}.`:r+=`of type ${s[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const ys=(r,...e)=>ws("Key must be ",r,...e);function bs(r,e,...s){return ws(`Key for the ${r} algorithm must be `,e,...s)}const Ss=r=>fs(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",at=["CryptoKey"],fn=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let s;for(const t of e){const n=Object.keys(t);if(!s||s.size===0){s=new Set(n);continue}for(const i of n){if(s.has(i))return!1;s.add(i)}}return!0};function _n(r){return typeof r=="object"&&r!==null}function ve(r){if(!_n(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const gn=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:s}=e.algorithm;if(typeof s!="number"||s<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function Ue(r){return ve(r)&&typeof r.kty=="string"}function xn(r){return r.kty!=="oct"&&typeof r.d=="string"}function mn(r){return r.kty!=="oct"&&typeof r.d>"u"}function wn(r){return Ue(r)&&r.kty==="oct"&&typeof r.k=="string"}function yn(r){let e,s;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},s=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},s=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},s=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},s=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new xe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:s}}const vs=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:s}=yn(r),t=[e,r.ext??!1,r.key_ops??s],n={...r};return delete n.alg,delete n.use,At.subtle.importKey("jwk",n,...t)},Es=r=>Re(r);let He,Be;const As=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ct=async(r,e,s,t,n=!1)=>{let i=r.get(e);if(i!=null&&i[t])return i[t];const o=await vs({...s,alg:t});return n&&Object.freeze(e),i?i[t]=o:r.set(e,{[t]:o}),o},bn={normalizePublicKey:(r,e)=>{if(As(r)){let s=r.export({format:"jwk"});return delete s.d,delete s.dp,delete s.dq,delete s.p,delete s.q,delete s.qi,s.k?Es(s.k):(Be||(Be=new WeakMap),ct(Be,r,s,e))}return Ue(r)?r.k?Re(r.k):(Be||(Be=new WeakMap),ct(Be,r,r,e,!0)):r},normalizePrivateKey:(r,e)=>{if(As(r)){let s=r.export({format:"jwk"});return s.k?Es(s.k):(He||(He=new WeakMap),ct(He,r,s,e))}return Ue(r)?r.k?Re(r.k):(He||(He=new WeakMap),ct(He,r,r,e,!0)):r}};async function Is(r,e){if(!ve(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new xe('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return vs({...r,alg:e});default:throw new xe('Unsupported "kty" (Key Type) Parameter value')}}const Fe=r=>r==null?void 0:r[Symbol.toStringTag],Ot=(r,e,s)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,s))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},Sn=(r,e,s,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ue(e)){if(wn(e)&&Ot(r,e,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Ss(e))throw new TypeError(bs(r,e,...at,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Fe(e)} instances for symmetric algorithms must be of type "secret"`)}},vn=(r,e,s,t)=>{if(t&&Ue(e))switch(s){case"sign":if(xn(e)&&Ot(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(mn(e)&&Ot(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Ss(e))throw new TypeError(bs(r,e,...at,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Fe(e)} instances for asymmetric algorithms must not be of type "secret"`);if(s==="sign"&&e.type==="public")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm signing must be of type "private"`);if(s==="decrypt"&&e.type==="public")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&s==="verify"&&e.type==="private")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&s==="encrypt"&&e.type==="private")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Ts(r,e,s,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Sn(e,s,t,r):vn(e,s,t,r)}Ts.bind(void 0,!1);const Rs=Ts.bind(void 0,!0);function En(r,e,s,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;s!==void 0?i=new Map([...Object.entries(s),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new xe(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new r(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new r(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const An=(r,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(s=>typeof s!="string")))throw new TypeError(`"${r}" option must be an array of strings`);if(e)return new Set(e)};function In(r,e){const s=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new xe(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function Tn(r,e,s){if(e=await bn.normalizePublicKey(e,r),fs(e))return pn(e,r,s),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(ys(e,...at));return At.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(ys(e,...at,"Uint8Array","JSON Web Key"))}const Rn=async(r,e,s,t)=>{const n=await Tn(r,e,"verify");gn(r,n);const i=In(r,n.algorithm);try{return await At.subtle.verify(i,n,s,t)}catch{return!1}};async function kn(r,e,s){if(!ve(r))throw new X("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new X('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new X("JWS Protected Header incorrect type");if(r.payload===void 0)throw new X("JWS Payload missing");if(typeof r.signature!="string")throw new X("JWS Signature missing or incorrect type");if(r.header!==void 0&&!ve(r.header))throw new X("JWS Unprotected Header incorrect type");let t={};if(r.protected)try{const v=Re(r.protected);t=JSON.parse(je.decode(v))}catch{throw new X("JWS Protected Header is invalid")}if(!fn(t,r.header))throw new X("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...r.header},i=En(X,new Map([["b64",!0]]),s==null?void 0:s.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new X('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new X('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&An("algorithms",s.algorithms);if(c&&!c.has(a))throw new _s('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof r.payload!="string")throw new X("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new X("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,r),l=!0,Rs(a,e,"verify"),Ue(e)&&(e=await Is(e,a))):Rs(a,e,"verify");const u=on(ot.encode(r.protected??""),ot.encode("."),typeof r.payload=="string"?ot.encode(r.payload):r.payload);let f;try{f=Re(r.signature)}catch{throw new X("Failed to base64url decode the signature")}if(!await Rn(a,e,f,u))throw new ms;let h;if(o)try{h=Re(r.payload)}catch{throw new X("Failed to base64url decode the payload")}else typeof r.payload=="string"?h=ot.encode(r.payload):h=r.payload;const x={payload:h};return r.protected!==void 0&&(x.protectedHeader=t),r.header!==void 0&&(x.unprotectedHeader=r.header),l?{...x,key:e}:x}async function On(r,e,s){if(r instanceof Uint8Array&&(r=je.decode(r)),typeof r!="string")throw new X("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=r.split(".");if(o!==3)throw new X("Invalid Compact JWS");const a=await kn({payload:n,protected:t,signature:i},e,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Pn=r=>Math.floor(r.getTime()/1e3),ks=60,Os=ks*60,Pt=Os*24,Cn=Pt*7,Nn=Pt*365.25,Ln=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ps=r=>{const e=Ln.exec(r);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const s=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(s*ks);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(s*Os);break;case"day":case"days":case"d":n=Math.round(s*Pt);break;case"week":case"weeks":case"w":n=Math.round(s*Cn);break;default:n=Math.round(s*Nn);break}return e[1]==="-"||e[4]==="ago"?-n:n},Cs=r=>r.toLowerCase().replace(/^application\//,""),Dn=(r,e)=>typeof r=="string"?e.includes(r):Array.isArray(r)?e.some(Set.prototype.has.bind(new Set(r))):!1,Mn=(r,e,s={})=>{let t;try{t=JSON.parse(je.decode(e))}catch{}if(!ve(t))throw new me("JWT Claims Set must be a top-level JSON object");const{typ:n}=s;if(n&&(typeof r.typ!="string"||Cs(r.typ)!==Cs(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=s,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const x of new Set(u.reverse()))if(!(x in t))throw new he(`missing required "${x}" claim`,t,x,"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&&!Dn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let f;switch(typeof s.clockTolerance){case"string":f=Ps(s.clockTolerance);break;case"number":f=s.clockTolerance;break;case"undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=s,h=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>h+f)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<=h-f)throw new It('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=h-t.iat,v=typeof l=="number"?l:Ps(l);if(x-f>v)throw new It('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-f)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function $n(r,e,s){var o;const t=await On(r,e,s);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new me("JWTs MUST NOT use unencoded payload");const i={payload:Mn(t.protectedHeader,t.payload,s),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Wn(r){switch(typeof r=="string"&&r.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new xe('Unsupported "alg" value for a JSON Web Key Set')}}function Un(r){return r&&typeof r=="object"&&Array.isArray(r.keys)&&r.keys.every(Hn)}function Hn(r){return ve(r)}function Ns(r){return typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}class Bn{constructor(e){if(this._cached=new WeakMap,!Un(e))throw new Tt("JSON Web Key Set malformed");this._jwks=Ns(e)}async getKey(e,s){const{alg:t,kid:n}={...e,...s==null?void 0:s.header},i=Wn(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 Rt;if(c!==1){const l=new gs,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const f of o)try{yield await Ls(u,f,t)}catch{}},l}return Ls(this._cached,a,t)}}async function Ls(r,e,s){const t=r.get(e)||r.set(e,{}).get(e);if(t[s]===void 0){const n=await Is({...e,ext:!0},s);if(n instanceof Uint8Array||n.type!=="public")throw new Tt("JSON Web Key Set members must be public keys");t[s]=n}return t[s]}function Ds(r){const e=new Bn(r),s=async(t,n)=>e.getKey(t,n);return Object.defineProperties(s,{jwks:{value:()=>Ns(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),s}const Fn=async(r,e,s)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(r.href,{signal:t?t.signal:void 0,redirect:"manual",headers:s.headers}).catch(a=>{throw i?new xs:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new ee("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new ee("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Kn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Ct;(typeof navigator>"u"||!((Mr=(yt=navigator.userAgent)==null?void 0:yt.startsWith)!=null&&Mr.call(yt,"Mozilla/5.0 ")))&&(Ct="jose/v5.10.0");const Nt=Symbol();function Gn(r,e){return!(typeof r!="object"||r===null||!("uat"in r)||typeof r.uat!="number"||Date.now()-r.uat>=e||!("jwks"in r)||!ve(r.jwks)||!Array.isArray(r.jwks.keys)||!Array.prototype.every.call(r.jwks.keys,ve))}class qn{constructor(e,s){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:s==null?void 0:s.agent,headers:s==null?void 0:s.headers},this._timeoutDuration=typeof(s==null?void 0:s.timeoutDuration)=="number"?s==null?void 0:s.timeoutDuration:5e3,this._cooldownDuration=typeof(s==null?void 0:s.cooldownDuration)=="number"?s==null?void 0:s.cooldownDuration:3e4,this._cacheMaxAge=typeof(s==null?void 0:s.cacheMaxAge)=="number"?s==null?void 0:s.cacheMaxAge:6e5,(s==null?void 0:s[Nt])!==void 0&&(this._cache=s==null?void 0:s[Nt],Gn(s==null?void 0:s[Nt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ds(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,s){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,s)}catch(t){if(t instanceof Rt&&this.coolingDown()===!1)return await this.reload(),this._local(e,s);throw t}}async reload(){this._pendingFetch&&Kn()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Ct&&!e.has("User-Agent")&&(e.set("User-Agent",Ct),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Fn(this._url,this._timeoutDuration,this._options).then(s=>{this._local=Ds(s),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=s),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(s=>{throw this._pendingFetch=void 0,s})),await this._pendingFetch}}function Jn(r,e){const s=new qn(r,e),t=async(n,i)=>s.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!s._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=s._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Vn=Re;function zn(r){if(typeof r!="string")throw new me("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new me("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new me("Invalid JWT");if(!e)throw new me("JWTs must contain a payload");let t;try{t=Vn(e)}catch{throw new me("Failed to base64url decode the payload")}let n;try{n=JSON.parse(je.decode(t))}catch{throw new me("Failed to parse the decoded payload as JSON")}if(!ve(n))throw new me("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ee(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function q(r,e,s=""){const t=Lt(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function Ms(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ee(r.outputLen),Ee(r.blockLen)}function Ke(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function $s(r,e){q(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Yn(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Ge(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Dt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ye(r,e){return r<<32-e|r>>>e}const jn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xn(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function Zn(r){for(let e=0;e<r.length;e++)r[e]=Xn(r[e]);return r}const Ws=jn?r=>r:Zn,Us=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qn=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Ze(r){if(q(r),Us)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Qn[r[s]];return e}const Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hs(r){if(r>=Ae._0&&r<=Ae._9)return r-Ae._0;if(r>=Ae.A&&r<=Ae.F)return r-(Ae.A-10);if(r>=Ae.a&&r<=Ae.f)return r-(Ae.a-10)}function lt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Us)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=Hs(r.charCodeAt(i)),a=Hs(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];q(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Bs(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Fs(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const ei=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function ti(r,e,s){return r&e^~r&s}function si(r,e,s){return r&e^r&s^e&s}class ri{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Dt(this.buffer)}update(e){Ke(this),q(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Dt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ke(this),$s(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,Ge(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Dt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),dt=BigInt(2**32-1),Ks=BigInt(32);function ni(r,e=!1){return e?{h:Number(r&dt),l:Number(r>>Ks&dt)}:{h:Number(r>>Ks&dt)|0,l:Number(r&dt)|0}}function ii(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=ni(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const oi=(r,e,s)=>r<<s|e>>>32-s,ai=(r,e,s)=>e<<s|r>>>32-s,ci=(r,e,s)=>e<<s-32|r>>>64-s,li=(r,e,s)=>r<<s-32|e>>>64-s,di=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pe=new Uint32Array(64);class ui extends ri{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let f=0;f<16;f++,s+=4)Pe[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const _=Pe[f-15],h=Pe[f-2],x=ye(_,7)^ye(_,18)^_>>>3,v=ye(h,17)^ye(h,19)^h>>>10;Pe[f]=v+Pe[f-7]+x+Pe[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const _=ye(a,6)^ye(a,11)^ye(a,25),h=u+_+ti(a,c,l)+di[f]+Pe[f]|0,v=(ye(t,2)^ye(t,13)^ye(t,22))+si(t,n,i)|0;u=l,l=c,c=a,a=o+h|0,o=i,i=n,n=t,t=h+v|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(){Ge(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}}class hi extends ui{constructor(){super(32);P(this,"A",Oe[0]|0);P(this,"B",Oe[1]|0);P(this,"C",Oe[2]|0);P(this,"D",Oe[3]|0);P(this,"E",Oe[4]|0);P(this,"F",Oe[5]|0);P(this,"G",Oe[6]|0);P(this,"H",Oe[7]|0)}}const pi=Bs(()=>new hi,ei(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mt=BigInt(0),$t=BigInt(1);function ut(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Gs(r){if(typeof r=="bigint"){if(!ft(r))throw new Error("positive bigint expected, got "+r)}else Ee(r);return r}function ht(r){const e=Gs(r).toString(16);return e.length&1?"0"+e:e}function qs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?Mt:BigInt("0x"+r)}function pt(r){return qs(Ze(r))}function Js(r){return qs(Ze(fi(q(r)).reverse()))}function Wt(r,e){Ee(e),r=Gs(r);const s=lt(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function Vs(r,e){return Wt(r,e).reverse()}function fi(r){return Uint8Array.from(r)}const ft=r=>typeof r=="bigint"&&Mt<=r;function _i(r,e,s){return ft(r)&&ft(e)&&ft(s)&&e<=r&&r<s}function gi(r,e,s,t){if(!_i(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function xi(r){let e;for(e=0;r>Mt;r>>=$t,e+=1);return e}const Ut=r=>($t<<BigInt(r))-$t;function mi(r,e,s){if(Ee(r,"hashLen"),Ee(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=E=>new Uint8Array(E),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},_=(...E)=>s(l,ke(c,...E)),h=(E=n)=>{l=_(i,E),c=_(),E.length!==0&&(l=_(o,E),c=_())},x=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let E=0;const T=[];for(;E<e;){c=_();const k=c.slice();T.push(k),E+=c.length}return ke(...T)};return(E,T)=>{f(),h(E);let k;for(;!(k=T(x()));)h();return f(),k}}function Ht(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(s,!0)}function zs(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),ne=BigInt(1),Le=BigInt(2),Ys=BigInt(3),js=BigInt(4),Xs=BigInt(5),wi=BigInt(7),Zs=BigInt(8),yi=BigInt(9),Qs=BigInt(16);function pe(r,e){const s=r%e;return s>=ae?s:e+s}function ue(r,e,s){let t=r;for(;e-- >ae;)t*=t,t%=s;return t}function er(r,e){if(r===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let s=pe(r,e),t=e,n=ae,i=ne;for(;s!==ae;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==ne)throw new Error("invert: does not exist");return pe(n,e)}function Bt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function tr(r,e){const s=(r.ORDER+ne)/js,t=r.pow(e,s);return Bt(r,t,e),t}function bi(r,e){const s=(r.ORDER-Xs)/Zs,t=r.mul(e,Le),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,Le),n),a=r.mul(i,r.sub(o,r.ONE));return Bt(r,a,e),a}function Si(r){const e=_t(r),s=sr(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+wi)/Qs;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const f=a.mul(l,n),_=a.mul(l,i),h=a.eql(a.sqr(u),c),x=a.eql(a.sqr(f),c);l=a.cmov(l,u,h),u=a.cmov(_,f,x);const v=a.eql(a.sqr(u),c),E=a.cmov(l,u,v);return Bt(a,E,c),E}}function sr(r){if(r<Ys)throw new Error("sqrt is not defined for small field");let e=r-ne,s=0;for(;e%Le===ae;)e/=Le,s++;let t=Le;const n=_t(r);for(;nr(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return tr;let i=n.pow(t,e);const o=(e+ne)/Le;return function(c,l){if(c.is0(l))return l;if(nr(c,l)!==1)throw new Error("Cannot find square root");let u=s,f=c.mul(c.ONE,i),_=c.pow(l,e),h=c.pow(l,o);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let x=1,v=c.sqr(_);for(;!c.eql(v,c.ONE);)if(x++,v=c.sqr(v),x===u)throw new Error("Cannot find square root");const E=ne<<BigInt(u-x-1),T=c.pow(f,E);u=x,f=c.sqr(T),_=c.mul(_,f),h=c.mul(h,T)}return h}}function vi(r){return r%js===Ys?tr:r%Zs===Xs?bi:r%Qs===yi?Si(r):sr(r)}const Ei=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ai(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Ei.reduce((t,n)=>(t[n]="function",t),e);return Ht(r,s),r}function Ii(r,e,s){if(s<ae)throw new Error("invalid exponent, negatives unsupported");if(s===ae)return r.ONE;if(s===ne)return e;let t=r.ONE,n=e;for(;s>ae;)s&ne&&(t=r.mul(t,n)),n=r.sqr(n),s>>=ne;return t}function rr(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function nr(r,e){const s=(r.ORDER-ne)/Le,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Ti(r,e){e!==void 0&&Ee(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ri{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ae);P(this,"ONE",ne);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=Ti(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 pe(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&ne)===ne}neg(e){return pe(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return pe(e*e,this.ORDER)}add(e,s){return pe(e+s,this.ORDER)}sub(e,s){return pe(e-s,this.ORDER)}mul(e,s){return pe(e*s,this.ORDER)}pow(e,s){return Ii(this,e,s)}div(e,s){return pe(e*er(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return er(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Vs(e,this.BYTES):Wt(e,this.BYTES)}fromBytes(e,s=!1){q(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?Js(e):pt(e);if(a&&(c=pe(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return rr(this,e)}cmov(e,s,t){return t?s:e}}function _t(r,e={}){return new Ri(r,e)}function ir(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function or(r){const e=ir(r);return e+Math.ceil(e/2)}function ki(r,e,s=!1){q(r);const t=r.length,n=ir(e),i=or(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?Js(r):pt(r),a=pe(o,e-ne)+ne;return s?Vs(a,n):Wt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),De=BigInt(1);function gt(r,e){const s=e.negate();return r?s:e}function ar(r,e){const s=rr(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function cr(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Ft(r,e){cr(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=Ut(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function lr(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,f=a===0,_=a<0,h=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:_,isNegF:h,offsetF:l}}const Kt=new WeakMap,dr=new WeakMap;function Gt(r){return dr.get(r)||1}function ur(r){if(r!==qe)throw new Error("invalid wNAF")}class Oi{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>qe;)s&De&&(t=t.add(n)),n=n.double(),s>>=De;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Ft(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Ft(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:_,offsetF:h}=lr(t,a,o);t=c,u?i=i.add(gt(_,s[h])):n=n.add(gt(f,s[l]))}return ur(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=Ft(e,this.bits);for(let o=0;o<i.windows&&t!==qe;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=lr(t,o,i);if(t=a,!l){const f=s[c];n=n.add(u?f.negate():f)}}return ur(t),n}getPrecomputes(e,s,t){let n=Kt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Kt.set(s,n))),n}cached(e,s,t){const n=Gt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=Gt(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){cr(s,this.bits),dr.set(e,s),Kt.delete(e)}hasCache(e){return Gt(e)!==1}}function Pi(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>qe||t>qe;)s&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),s>>=De,t>>=De;return{p1:i,p2:o}}function hr(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ai(e),e}else return _t(r,{isLE:s})}function Ci(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>qe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=hr(e.p,s.Fp,t),i=hr(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Ni(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class pr{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(Ms(e),q(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ge(n)}update(e){return Ke(this),this.iHash.update(e),this}digestInto(e){Ke(this),q(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const fr=(r,e,s)=>new pr(r,e).update(s).digest();fr.create=(r,e)=>new pr(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _r=(r,e)=>(r+(r>=0?e:-e)/gr)/e;function Li(r,e,s){const[[t,n],[i,o]]=e,a=_r(o*r,s),c=_r(-n*r,s);let l=r-a*t-c*i,u=-a*n-c*o;const f=l<Ie,_=u<Ie;f&&(l=-l),_&&(u=-u);const h=Ut(Math.ceil(xi(s)/2))+Je;if(l<Ie||l>=h||u<Ie||u>=h)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:_,k2:u}}function qt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Jt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ut(s.lowS,"lowS"),ut(s.prehash,"prehash"),s.format!==void 0&&qt(s.format),s}class Di extends Error{constructor(e=""){super(e)}}const Ce={Err:Di,_tlv:{encode:(r,e)=>{const{Err:s}=Ce;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=ht(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?ht(n.length/2|128):"";return ht(r)+i+n+e},decode(r,e){const{Err:s}=Ce;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Ce;if(r<Ie)throw new e("integer: negative integers are not allowed");let s=ht(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Ce;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return pt(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Ce,n=q(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Ce,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Je=BigInt(1),gr=BigInt(2),xt=BigInt(3),Mi=BigInt(4);function $i(r,e={}){const s=Ci("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;Ht(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=mr(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,m,w){const{x:I,y:O}=m.toAffine(),D=t.toBytes(I);if(ut(w,"isCompressed"),w){u();const y=!t.isOdd(O);return ke(xr(y),D)}else return ke(Uint8Array.of(4),D,t.toBytes(O))}function _(M){q(M,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,I=M.length,O=M[0],D=M.subarray(1);if(I===m&&(O===2||O===3)){const y=t.fromBytes(D);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const b=v(y);let S;try{S=t.sqrt(b)}catch(H){const W=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}u();const A=t.isOdd(S);return(O&1)===1!==A&&(S=t.neg(S)),{x:y,y:S}}else if(I===w&&O===4){const y=t.BYTES,b=t.fromBytes(D.subarray(0,y)),S=t.fromBytes(D.subarray(y,y*2));if(!E(b,S))throw new Error("bad point: is not on curve");return{x:b,y:S}}else throw new Error(`bad point: got length ${I}, expected compressed=${m} or uncompressed=${w}`)}const h=e.toBytes||f,x=e.fromBytes||_;function v(M){const m=t.sqr(M),w=t.mul(m,M);return t.add(t.add(w,t.mul(M,i.a)),i.b)}function E(M,m){const w=t.sqr(m),I=v(M);return t.eql(w,I)}if(!E(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const T=t.mul(t.pow(i.a,xt),Mi),k=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(T,k)))throw new Error("bad curve params: a or b");function B(M,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${M}`);return m}function $(M){if(!(M instanceof j))throw new Error("Weierstrass Point expected")}function J(M){if(!c||!c.basises)throw new Error("no endo");return Li(M,c.basises,n.ORDER)}const G=zs((M,m)=>{const{X:w,Y:I,Z:O}=M;if(t.eql(O,t.ONE))return{x:w,y:I};const D=M.is0();m==null&&(m=D?t.ONE:t.inv(O));const y=t.mul(w,m),b=t.mul(I,m),S=t.mul(O,m);if(D)return{x:t.ZERO,y:t.ZERO};if(!t.eql(S,t.ONE))throw new Error("invZ was invalid");return{x:y,y:b}}),se=zs(M=>{if(M.is0()){if(e.allowInfinityPoint&&!t.is0(M.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=M.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!E(m,w))throw new Error("bad point: equation left != right");if(!M.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(M,m,w,I,O){return w=new j(t.mul(w.X,M),w.Y,w.Z),m=gt(I,m),w=gt(O,w),m.add(w)}const C=class C{constructor(m,w,I){P(this,"X");P(this,"Y");P(this,"Z");this.X=B("x",m),this.Y=B("y",w,!0),this.Z=B("z",I),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:I}=m||{};if(!m||!t.isValid(w)||!t.isValid(I))throw new Error("invalid affine point");if(m instanceof C)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(I)?C.ZERO:new C(w,I,t.ONE)}static fromBytes(m){const w=C.fromAffine(x(q(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return C.fromBytes(lt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return U.createCache(this,m),w||this.multiply(xt),this}assertValidity(){se(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){$(m);const{X:w,Y:I,Z:O}=this,{X:D,Y:y,Z:b}=m,S=t.eql(t.mul(w,b),t.mul(D,O)),A=t.eql(t.mul(I,b),t.mul(y,O));return S&&A}negate(){return new C(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,I=t.mul(w,xt),{X:O,Y:D,Z:y}=this;let b=t.ZERO,S=t.ZERO,A=t.ZERO,R=t.mul(O,O),H=t.mul(D,D),W=t.mul(y,y),N=t.mul(O,D);return N=t.add(N,N),A=t.mul(O,y),A=t.add(A,A),b=t.mul(m,A),S=t.mul(I,W),S=t.add(b,S),b=t.sub(H,S),S=t.add(H,S),S=t.mul(b,S),b=t.mul(N,b),A=t.mul(I,A),W=t.mul(m,W),N=t.sub(R,W),N=t.mul(m,N),N=t.add(N,A),A=t.add(R,R),R=t.add(A,R),R=t.add(R,W),R=t.mul(R,N),S=t.add(S,R),W=t.mul(D,y),W=t.add(W,W),R=t.mul(W,N),b=t.sub(b,R),A=t.mul(W,H),A=t.add(A,A),A=t.add(A,A),new C(b,S,A)}add(m){$(m);const{X:w,Y:I,Z:O}=this,{X:D,Y:y,Z:b}=m;let S=t.ZERO,A=t.ZERO,R=t.ZERO;const H=i.a,W=t.mul(i.b,xt);let N=t.mul(w,D),K=t.mul(I,y),Y=t.mul(O,b),de=t.add(w,I),V=t.add(D,y);de=t.mul(de,V),V=t.add(N,K),de=t.sub(de,V),V=t.add(w,O);let oe=t.add(D,b);return V=t.mul(V,oe),oe=t.add(N,Y),V=t.sub(V,oe),oe=t.add(I,O),S=t.add(y,b),oe=t.mul(oe,S),S=t.add(K,Y),oe=t.sub(oe,S),R=t.mul(H,V),S=t.mul(W,Y),R=t.add(S,R),S=t.sub(K,R),R=t.add(K,R),A=t.mul(S,R),K=t.add(N,N),K=t.add(K,N),Y=t.mul(H,Y),V=t.mul(W,V),K=t.add(K,Y),Y=t.sub(N,Y),Y=t.mul(H,Y),V=t.add(V,Y),N=t.mul(K,V),A=t.add(A,N),N=t.mul(oe,V),S=t.mul(de,S),S=t.sub(S,N),N=t.mul(de,K),R=t.mul(oe,R),R=t.add(R,N),new C(S,A,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(C.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let I,O;const D=y=>U.cached(this,y,b=>ar(C,b));if(w){const{k1neg:y,k1:b,k2neg:S,k2:A}=J(m),{p:R,f:H}=D(b),{p:W,f:N}=D(A);O=H.add(N),I=F(w.beta,R,W,y,S)}else{const{p:y,f:b}=D(m);I=y,O=b}return ar(C,[I,O])[0]}multiplyUnsafe(m){const{endo:w}=e,I=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ie||I.is0())return C.ZERO;if(m===Je)return I;if(U.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:D,k2neg:y,k2:b}=J(m),{p1:S,p2:A}=Pi(C,I,D,b);return F(w.beta,S,A,O,y)}else return U.unsafe(I,m)}toAffine(m){return G(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Je?!0:m?m(C,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Je?this:m?m(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return ut(m,"isCompressed"),this.assertValidity(),h(C,this,m)}toHex(m=!0){return Ze(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(C,"BASE",new C(i.Gx,i.Gy,t.ONE)),P(C,"ZERO",new C(t.ZERO,t.ONE,t.ZERO)),P(C,"Fp",t),P(C,"Fn",n);let j=C;const re=n.BITS,U=new Oi(j,e.endo?Math.ceil(re/2):re);return j.BASE.precompute(8),j}function xr(r){return Uint8Array.of(r?2:3)}function mr(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wi(r,e={}){const{Fn:s}=r,t=e.randomBytes||Fs,n=Object.assign(mr(r.Fp,s),{seed:or(s.ORDER)});function i(h){try{const x=s.fromBytes(h);return s.isValidNot0(x)}catch{return!1}}function o(h,x){const{publicKey:v,publicKeyUncompressed:E}=n;try{const T=h.length;return x===!0&&T!==v||x===!1&&T!==E?!1:!!r.fromBytes(h)}catch{return!1}}function a(h=t(n.seed)){return ki(q(h,n.seed,"seed"),s.ORDER)}function c(h,x=!0){return r.BASE.multiply(s.fromBytes(h)).toBytes(x)}function l(h){const{secretKey:x,publicKey:v,publicKeyUncompressed:E}=n;if(!Lt(h)||"_lengths"in s&&s._lengths||x===v)return;const T=q(h,void 0,"key").length;return T===v||T===E}function u(h,x,v=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const E=s.fromBytes(h);return r.fromBytes(x).multiply(E).toBytes(v)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=Ni(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:_,Point:r,utils:f,lengths:n})}function Ui(r,e,s={}){Ms(e),Ht(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Fs,n=s.hmac||((m,w)=>fr(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:h}=Wi(r,s),x={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},v=a*gr<i.ORDER;function E(m){const w=a>>Je;return m>w}function T(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function k(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(m,w){qt(w);const I=h.signature,O=w==="compact"?I:w==="recovered"?I+1:void 0;return q(m,O)}class ${constructor(w,I,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=T("r",w),this.s=T("s",I),O!=null){if(k(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,I=x.format){B(w,I);let O;if(I==="der"){const{r:S,s:A}=Ce.toSig(q(w));return new $(S,A)}I==="recovered"&&(O=w[0],I="compact",w=w.subarray(1));const D=h.signature/2,y=w.subarray(0,D),b=w.subarray(D,D*2);return new $(o.fromBytes(y),o.fromBytes(b),O)}static fromHex(w,I){return this.fromBytes(lt(w),I)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new $(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:O}=this,D=this.assertRecovery(),y=D===2||D===3?I+a:I;if(!i.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const b=i.toBytes(y),S=r.fromBytes(ke(xr((D&1)===0),b)),A=o.inv(y),R=G(q(w,void 0,"msgHash")),H=o.create(-R*A),W=o.create(O*A),N=r.BASE.multiplyUnsafe(H).add(S.multiplyUnsafe(W));if(N.is0())throw new Error("invalid recovery: point at infinify");return N.assertValidity(),N}hasHighS(){return E(this.s)}toBytes(w=x.format){if(qt(w),w==="der")return lt(Ce.hexFromSig(this));const{r:I,s:O}=this,D=o.toBytes(I),y=o.toBytes(O);return w==="recovered"?(k(),ke(Uint8Array.of(this.assertRecovery()),D,y)):ke(D,y)}toHex(w){return Ze(this.toBytes(w))}}const J=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const I=pt(w),O=w.length*8-c;return O>0?I>>BigInt(O):I},G=s.bits2int_modN||function(w){return o.create(J(w))},se=Ut(c);function F(m){return gi("num < 2^"+c,m,Ie,se),o.toBytes(m)}function j(m,w){return q(m,void 0,"message"),w?q(e(m),void 0,"prehashed message"):m}function re(m,w,I){const{lowS:O,prehash:D,extraEntropy:y}=Jt(I,x);m=j(m,D);const b=G(m),S=o.fromBytes(w);if(!o.isValidNot0(S))throw new Error("invalid private key");const A=[F(S),F(b)];if(y!=null&&y!==!1){const N=y===!0?t(h.secretKey):y;A.push(q(N,void 0,"extraEntropy"))}const R=ke(...A),H=b;function W(N){const K=J(N);if(!o.isValidNot0(K))return;const Y=o.inv(K),de=r.BASE.multiply(K).toAffine(),V=o.create(de.x);if(V===Ie)return;const oe=o.create(Y*o.create(H+V*S));if(oe===Ie)return;let $r=(de.x===V?0:2)|Number(de.y&Je),Wr=oe;return O&&E(oe)&&(Wr=o.neg(oe),$r^=1),new $(V,Wr,v?void 0:$r)}return{seed:R,k2sig:W}}function U(m,w,I={}){const{seed:O,k2sig:D}=re(m,w,I);return mi(e.outputLen,o.BYTES,n)(O,D).toBytes(I.format)}function C(m,w,I,O={}){const{lowS:D,prehash:y,format:b}=Jt(O,x);if(I=q(I,void 0,"publicKey"),w=j(w,y),!Lt(m)){const S=m instanceof $?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+S)}B(m,b);try{const S=$.fromBytes(m,b),A=r.fromBytes(I);if(D&&S.hasHighS())return!1;const{r:R,s:H}=S,W=G(w),N=o.inv(H),K=o.create(W*N),Y=o.create(R*N),de=r.BASE.multiplyUnsafe(K).add(A.multiplyUnsafe(Y));return de.is0()?!1:o.create(de.x)===R}catch{return!1}}function M(m,w,I={}){const{prehash:O}=Jt(I,x);return w=j(w,O),$.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:_,lengths:h,Point:r,sign:U,verify:C,recoverPublicKey:M,Signature:$,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Hi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},wr=BigInt(2);function Bi(r){const e=Vt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,f=ue(u,s,e)*u%e,_=ue(f,s,e)*u%e,h=ue(_,wr,e)*l%e,x=ue(h,n,e)*h%e,v=ue(x,i,e)*x%e,E=ue(v,a,e)*v%e,T=ue(E,c,e)*E%e,k=ue(T,a,e)*v%e,B=ue(k,s,e)*u%e,$=ue(B,o,e)*x%e,J=ue($,t,e)*l%e,G=ue(J,wr,e);if(!zt.eql(zt.sqr(G),r))throw new Error("Cannot find square root");return G}const zt=_t(Vt.p,{sqrt:Bi}),Fi=Ui($i(Vt,{Fp:zt,endo:Hi}),pi),Ki=BigInt(0),Qe=BigInt(1),Gi=BigInt(2),qi=BigInt(7),Ji=BigInt(256),Vi=BigInt(113),yr=[],br=[],Sr=[];for(let r=0,e=Qe,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],yr.push(2*(5*t+s)),br.push((r+1)*(r+2)/2%64);let n=Ki;for(let i=0;i<7;i++)e=(e<<Qe^(e>>qi)*Vi)%Ji,e&Gi&&(n^=Qe<<(Qe<<BigInt(i))-Qe);Sr.push(n)}const vr=ii(Sr,!0),zi=vr[0],Yi=vr[1],Er=(r,e,s)=>s>32?ci(r,e,s):oi(r,e,s),Ar=(r,e,s)=>s>32?li(r,e,s):ai(r,e,s);function ji(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],u=s[c+1],f=Er(l,u,1)^s[a],_=Ar(l,u,1)^s[a+1];for(let h=0;h<50;h+=10)r[o+h]^=f,r[o+h+1]^=_}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=br[o],c=Er(n,i,a),l=Ar(n,i,a),u=yr[o];n=r[u],i=r[u+1],r[u]=c,r[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=zi[t],r[1]^=Yi[t]}Ge(s)}class Yt{constructor(e,s,t,n=!1,i=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,Ee(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Yn(this.state)}clone(){return this._cloneInto()}keccak(){Ws(this.state32),ji(this.state32,this.rounds),Ws(this.state32),this.posOut=0,this.pos=0}update(e){Ke(this),q(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ke(this,!1),q(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(s.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ee(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($s(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ge(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Yt(s,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Ir=((r,e,s,t={})=>Bs(()=>new Yt(e,r,s),t))(1,136,32),Xi=60;class Zi{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Jn(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Xi<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 $n(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 zn(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
-
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Ir(i),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Qi(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],_=f>=27?f-27:f,v=new Fi.Signature(Tr(l),Tr(u)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),E=Ir(v);return"0x"+Ze(E.slice(12))}}function Qi(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function Tr(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const eo=3e4,to=1e3;class so{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,to*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??eo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const ro=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Me{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=Me.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Me.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Me.generateRandom16Hex(),l=Me.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",f=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const _=window.open(f,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const h=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),$(),t(new Error("Authentication timeout"))},5*60*1e3),x=10,v=30;let E=0,T=null;const k=()=>{clearInterval(B),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),T=setTimeout(()=>{$(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},B=setInterval(()=>{E++;try{_.closed&&(E<=x?k():($(),t(new Error("로그인이 취소되었습니다"))))}catch{k()}},1e3),$=()=>{clearTimeout(h),clearInterval(B),T&&clearTimeout(T),window.removeEventListener("message",J)},J=G=>{if(G.origin!==e.expectedOrigin)return;if(!ro.has(G.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",G.origin),$(),t(new Error("Unauthorized OAuth origin"));return}$();const se=typeof G.data.status=="string",F=se?G.data.data??{}:G.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:se?"wrapped":"flat",status:se?G.data.status:"(flat)"});const j=(F==null?void 0:F.state)??G.data.state;if(!j||j!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(se&&G.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",F==null?void 0:F.error),t(new Error((F==null?void 0:F.error)||"Authentication failed"));return}if(!se&&(F!=null&&F.error)){d.error("[CROSSx] OAuth 실패:",F.error),t(new Error(F.error||"Authentication failed"));return}const re=F==null?void 0:F.idToken,U=F==null?void 0:F.accessToken,C=U??re,M=(F==null?void 0:F.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!re,hasEmail:!!M}),!C){d.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const m={token:C,email:M},w=I=>{Me.verifyIdTokenNonce(I,l).then(()=>s(m)).catch(O=>{d.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?w(U):re?w(re):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):re?w(re):t(new Error("Token not found in response"))};window.addEventListener("message",J)})}}const et="crossx_wallet_data",Ve="crossx_mock_pin_hash";class no{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(et)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(et);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(et,n);const i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(Ve,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(et);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Ve);return s&&s!==e?!1:(s||await this.storage.set(Ve,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(p.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ve);if(n&&t&&n!==t)throw new g(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ve,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new g(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new g(p.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(et,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ve,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class $e{constructor(e,s,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(hs))return e;const s=!e||this.tokenStore.isExpiringSoon(hs);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,s,t,n=!1){var c,l,u,f;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const h=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(h&&typeof h.code=="number"){if(h.code<0||h.code>=400){const x=h.message||h.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:h.code,message:x,url:o,method:e});const v=$e.mapGatewayError(h.code,h.data);if(v===p.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(v===p.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(p.USER_NOT_FOUND,$e.getGatewayErrorMessage(h.code,x));const E=v===p.AUTH_NOT_AUTHENTICATED?p.SESSION_EXPIRED:v,T=E===p.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":$e.getGatewayErrorMessage(h.code,x),k=h.data,B=v===p.PIN_LOCKED?$e.extractLockDetails(k):k??void 0;throw new g(E,T,B)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:h.code,url:o,method:e}),h.data??h}return h}catch(_){if(_ instanceof g)throw _;const h=((l=_.response)==null?void 0:l.status)??_.status;if((h===401||h===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${h} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(p.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=_.response)!=null&&u.data){const x=_.response.data,v=x.message||x.data||"API 요청에 실패했습니다",E=x.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:v,url:o,method:e,status:(f=_.response)==null?void 0:f.status}),new g(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${v}`)}throw _}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new g(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new g(p.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new g(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,s,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new g(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new g(p.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new g(p.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10007:return p.BROADCAST_FAILED;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10004:return p.WALLET_ALREADY_EXISTS;case-10005:return p.WALLET_NOT_FOUND;case-10011:return p.WALLET_NOT_FOUND;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10013:return p.WITHDRAW_FAILED;case-10033:return p.USER_NOT_FOUND;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10025:return p.INVALID_APP_TYPE;case-10028:return $e.hasLockInfo(s)?p.PIN_LOCKED:p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10032:return p.PIN_REPEATED_PATTERN;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10040:return p.HMAC_REQUIRED;case-10041:return p.HMAC_VERIFICATION_FAILED;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class tt{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=tt.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?tn:en;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new g(tt.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=tt.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new g(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(st).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const Rr="__crossx-confirm-style",te="__crossx-confirm-overlay",io={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 kr(r,e){const s=io[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const oo=`
|
|
5
|
+
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_appleAccount:"Apple account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},zr={ko:Vr,en:os};function Se(r="en",e){return zr[r]??os}const as="crossx_access_token",cs="crossx_refresh_token",ls="crossx_user_info",yt=class yt{constructor(e,s,t,n,i,o,a){this.config=e,this.storage=s,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"}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const s=e==null?void 0:e.data;if(typeof s=="object"&&s!==null&&"code"in s){const t=s;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,s){const t=this.extractResponseErrorCode(e);if(t)throw new g(h.AUTH_FAILED,`${s} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let s,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;u.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});s=c.token,t=c.email,u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")"),t&&u.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){u.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new g(h.OAUTH_POPUP_BLOCKED,i):new g(h.AUTH_FAILED,i)}return this.processFirebaseToken(s,t)}async executeWithOAuthToken(e){return u.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,s){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:d}=this.config,{accessToken:f,refreshToken:_}=await this.exchangeFirebaseToken(e,d);let p,x,S;try{const I=this.crypto.decodeJWT(e);u.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),x=(i=I.firebase)==null?void 0:i.sign_in_provider;const k=((o=I.firebase)==null?void 0:o.identities)??{};S=I.email??((a=k.email)==null?void 0:a[0]),x==="google.com"?p=(c=k["google.com"])==null?void 0:c[0]:x==="apple.com"&&(p=(l=k["apple.com"])==null?void 0:l[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!p,"email:",S??"(없음)")}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const I=this.crypto.decodeJWT(f);u.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const k=await this.crypto.verifyJWT(f);if(n=k.signatureVerified??!1,!k.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const B=k.payload,$=B.email??S??s;u.log("[CROSSx] email 소스 — CROSSx JWT:",B.email??"(없음)","/ Firebase JWT:",S??"(없음)","/ OAuth 콜백:",s??"(없음)","→",$??"(없음)"),t={id:B.sub,email:$,signInProvider:x,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),_&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,_):_&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??s,signInProvider:x,providerSub:p},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}u.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const E=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,E),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(d){return u.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",d),{success:!1,error:d instanceof Error?d.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new g(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const s=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){const s=e instanceof g&&e.code===h.SESSION_EXPIRED;return u.log("[CROSSx] restoreSession —",s?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),s&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,i={};if(!t){const d=this.tokenStore.get()??"";d&&(i.access_token=d),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const d=yt.REFRESH_RELOGIN_CODES.has(c.code);throw new g(d?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new g(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const d=this.extractRefreshToken(a);d&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,d)}return u.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(u.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof g&&e.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):u.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,s){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!s)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;u.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return u.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(ls);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(as);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(cs);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(ls),await this.storage.remove(as),await this.storage.remove(cs),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",i),i==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof g&&i.code===h.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof g&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}};yt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let vt=yt;class Yr{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class jr{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new g(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Et{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let i=0;i<s.length;i++)n[i]=s[i]^t[i];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Xr{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new g(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Zr{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}var nt={environment:"production"};const Ue={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function Qr(r){const e=r.environment;return e&&e in Ue?Ue[e]:null}function en(){try{if(typeof nt<"u"){const r=typeof nt=="string"?JSON.parse(nt):nt,e=Qr(r);if(e)return e}}catch{}try{const r=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(r&&r in Ue)return Ue[r]}catch{}return Ue.production}const tn=2e3,ds=6e4,sn=1e3,rn=1e4,nn="0x77359400",us="0x3B9ACA00",hs=130,ps=6,fs=18,_s=3e4,on=5*60*1e3,an=30*1e3;function je(r,e="Apple account"){if(r.endsWith("@privaterelay.appleid.com"))return e;const s=r.indexOf("@");if(s<0)return"*".repeat(r.length||3);const t=r.substring(0,s),n=r.substring(s);return t.length<=1?`${t}${"*".repeat(Math.max(t.length,1))}${n}`:`${t[0]}${"*".repeat(t.length-1)}${n}`}const Q=class Q extends Zr{constructor(e,s,t,n,i,o,a,c,l,d,f){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=s,e.logger&&is(e.logger),this.confirmation=l,this.pinStore=f??new Et,this.chainRegistry=d,this.jsonRpc=new Xr(d,i),this.signInUseCase=new vt(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Yr(this.internalConfig,t,c),this.migrateWalletUseCase=new jr(t,a),(_=a.setOnUnauthorized)==null||_.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var s,t;u.log("[CROSSx SDK] v2.0.1 초기화 중..."),this.confirmation.setMessages(Se(this._config.locale));try{const n=en();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const i=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===h.PIN_CANCELLED))throw o;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,u.info("[CROSSx SDK] v2.0.1 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??null}catch(n){throw new g(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({connectOtherWallets:Kr(this._config)});if(t===null)return{success:!1,error:"User cancelled login"};if(t.type==="external")throw this.emit("connectExternalWallet",{walletId:t.walletId}),new g(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");s={...e,provider:t.provider}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof g?t:new g(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...s,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}catch(t){throw t instanceof g&&t.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw new g(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new g(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new g(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new g(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof g&&s.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof g?s:new g(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.ensurePinForSigning();const n=s.length,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return s.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(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof g?s:new g(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),s=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};s(e.matches);const t=n=>s(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Se(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof g&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof g&&s.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new g(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){return this.withSessionRecovery(()=>this._signMessage(e,s,t))}async _signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(h.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:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,o.signature,n.address),{chainId:e,signature:o.signature,message:s,address:n.address}}catch(o){throw o instanceof g?o:new g(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,s,t){return this.withSessionRecovery(()=>this._signTypedData(e,s,t))}async _signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new g(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");Q.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new g(h.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:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return Q.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof g?o:new g(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,s){return this.signTypedData(Q.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){return this.withSessionRecovery(()=>this._signTransaction(e,s,t))}async _signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=St(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(h.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return Q.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(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,s,t){return this.withSessionRecovery(()=>this._sendTransaction(e,s,t))}async _sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new g(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=St(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(h.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof g)throw a;const c=a instanceof Error?a.message:String(a);throw new g(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??sn,i=rn,o=t.timeoutMs??ds,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,i)}throw new g(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var S,E;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,s,o),c=n??((S=this._config.receiptPolling)==null?void 0:S.intervalMs)??tn,l=i??((E=this._config.receiptPolling)==null?void 0:E.timeoutMs)??ds,d=St(e),f=s.from??"";let _,p;const x=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{_=I;const k=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),B=s.value?BigInt(s.value):0n,$=Q.formatTxAmount(s.value,d.symbol,d.decimals),J=Q.formatTxAmount("0x"+k.toString(16),d.symbol,d.decimals),G=Q.formatTxAmount("0x"+(B+k).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??s.to,amount:$,fees:J,total:G,nativeSymbol:d.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(p=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:f,to:s.to,amount:Q.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:s.to},x),p)throw p;return{chainId:e,txHash:a,receipt:_}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new g(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof g?n:new g(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const i=n instanceof Error?n.message:String(n);throw new g(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new g(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:Q.formatWei(n),chainId:e}}catch(t){if(t instanceof g)throw t;const n=t instanceof Error?t.message:String(t);throw new g(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(fs),n=s/t,o=(s%t).toString().padStart(fs,"0").replace(/0+$/,"").slice(0,ps);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new ns(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof g)throw n;const i=n instanceof Error?n.message:String(n);throw new g(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,s,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,ps).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${s}`}catch{return}}async handleMigrationFlow(e){var c,l,d;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(f===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const _=await((d=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:d.call(l,f,e));if(!_){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(_.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const p=_.pinStatus;if(o=p.maxAttempts,i=o-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const x=p.lockExpiresAt*1e3,S=Math.max(1,Math.round((x-Date.now())/1e3)),E=S<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${S}초, 메시지: ${E}`),await this.confirmation.showRecoveryPinLockedPrompt(S,E),i=0,n="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(_){if(!(_ instanceof g))throw _;if(_.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const p=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:this.userEmail?je(this.userEmail,p.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){u.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.clearAuthState(),_}if(_.code===h.MIGRATION_PIN_LOCKED){const p=_.details;if(o=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const x=((p==null?void 0:p.lockExpiresAt)??0)*1e3,S=Math.max(1,Math.round((x-Date.now())/1e3)),E=S<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${S}초`),await this.confirmation.showRecoveryPinLockedPrompt(S,E),i=0,n="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",_),_}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const f=await this.migrateWalletUseCase.execute(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof g&&f.code===h.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof g&&f.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const _=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:_.sessionAlert_title,message:_.alert_sessionExpired,email:this.userEmail?je(this.userEmail,_.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success){u.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const S=await this.migrateWalletUseCase.execute(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",S.address),S}catch(S){throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",S),S}}throw this.clearAuthState(),f}throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,s){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,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&&u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[d,f,_]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,i?this.estimateGas(e,s):null,o?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const p=_;if(p){const x=us;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(x)).toString(16),c.maxPriorityFeePerGas=x,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=nn,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=us,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=Q.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new g(h.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(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new g(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==hs)throw new g(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${hs} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new g(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new g(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof g)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,i;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=Q.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&&(u.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){var n,i;this.ensureInitialized();const e=this.providerSub,s=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(f){throw this.clearAuthState(),f}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:s?!!l&&s===l:!0)){u.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=Se(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?je(this.userEmail,f.sessionAlert_appleAccount):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{u.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return u.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(s){const t=Se(this._config.locale??"en"),n=this.userEmail?je(this.userEmail,t.sessionAlert_appleAccount):void 0;if(s instanceof g&&s.code===h.WITHDRAW_FAILED){if(u.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(s instanceof g&&s.code===h.WALLET_NOT_FOUND){if(u.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),s}if(!(s instanceof g)||s.code!==h.SESSION_EXPIRED)throw s;if(u.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new g(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new g(h.SESSION_EXPIRED,o.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(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=Se(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n});if(!l)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(d){if(this.pinStore.clear(),d instanceof g){if(d.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(d.code===h.PIN_INVALID)return{ok:!1,error:d.message};if(d.code===h.PIN_LOCKED)return Q.buildPinLockedResult(d,a)}throw d}}});if(!c)throw new g(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof g&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?je(this.userEmail,l.sessionAlert_appleAccount):void 0})==="signin-again"&&(await this.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this._verifyPinMutex=null}}static parsePinError(e,s){if(e.code===h.PIN_WRONG)return{errorMessage:s.pinInput_error};if(e.code===h.PIN_INVALID)return{errorMessage:e.message};if(e.code===h.PIN_LOCKED){const t=e.details;return t!=null&&t.permanent?{errorMessage:s.pinLocked_permanent}:(t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts?{errorMessage:s.pinInput_error,attemptCount:t.maxAttempts-t.remainingAttempts,maxAttempts:t.maxAttempts}:{errorMessage:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}return null}static buildPinLockedResult(e,s){const t=Q.parsePinError(e,s);if(!t)return{ok:!1,error:e.message};const{errorMessage:n,...i}=t;return{ok:!1,error:n,...i}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const i=e!==void 0?t.find(o=>o.index===e)??t[0]:t[0];this.address=i.address,this.activeWalletIndex=i.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:i.address,index:i.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){const s=Se(this._config.locale??"en");let t=null;try{return await e()}catch(n){if(n instanceof g){if(t=Q.parsePinError(n,s),!t)throw n}else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t.errorMessage),this.pinStore.clear(),await this.ensureVerifiedPin(t.errorMessage,t.lockExpiresAt,t.attemptCount,t.maxAttempts);try{return await e()}catch(n){if(n instanceof g&&(t=Q.parsePinError(n,s),t))continue;throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new g(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new g(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new g(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),is(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};Q.OFFCHAIN_CHAIN_ID="0";let it=Q;class cn{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const At="crossx-sdk",ln=1,ge="data",Ne="keys",ot="aes-primary",dn=12;class gs{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,ln);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ge)||i.createObjectStore(ge),i.objectStoreNames.contains(Ne)||i.createObjectStore(Ne)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(s);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,s,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(s);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((s,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>s(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,ot);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,ot,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===At)return null;try{const e=await this.openDB(At),s=e.transaction([Ne,ge],"readonly"),t=s.objectStore(Ne).get(ot),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const i=s.objectStore(ge).getAll(),o=s.objectStore(ge).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)}),new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)})]);e.close(),await this.idbPut(Ne,ot,n);for(let l=0;l<c.length;l++)await this.idbPut(ge,String(c[l]),a[l]);return indexedDB.deleteDatabase(At),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(dn);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(ge,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(ge,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ge,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(ge)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const It=crypto,xs=r=>r instanceof CryptoKey,at=new TextEncoder,Xe=new TextDecoder;function un(...r){const e=r.reduce((n,{length:i})=>n+i,0),s=new Uint8Array(e);let t=0;for(const n of r)s.set(n,t),t+=n.length;return s}const hn=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},Re=r=>{let e=r;e instanceof Uint8Array&&(e=Xe.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return hn(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class ee extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}ee.code="ERR_JOSE_GENERIC";class he extends ee{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class Tt extends ee{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}Tt.code="ERR_JWT_EXPIRED";class ms extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}ms.code="ERR_JOSE_ALG_NOT_ALLOWED";class xe extends ee{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}xe.code="ERR_JOSE_NOT_SUPPORTED";class pn extends ee{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}pn.code="ERR_JWE_DECRYPTION_FAILED";class fn extends ee{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}fn.code="ERR_JWE_INVALID";class Z extends ee{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Z.code="ERR_JWS_INVALID";class me extends ee{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}me.code="ERR_JWT_INVALID";class _n extends ee{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}_n.code="ERR_JWK_INVALID";class Rt extends ee{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Rt.code="ERR_JWKS_INVALID";class kt extends ee{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}kt.code="ERR_JWKS_NO_MATCHING_KEY";class ws extends ee{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}ws.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ys extends ee{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}ys.code="ERR_JWKS_TIMEOUT";class bs extends ee{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}bs.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(r,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${r}`)}function Ze(r,e){return r.name===e}function Ot(r){return parseInt(r.name.slice(4),10)}function gn(r){switch(r){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function xn(r,e){if(e.length&&!e.some(s=>r.usages.includes(s))){let s="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();s+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?s+=`one of ${e[0]} or ${e[1]}.`:s+=`${e[0]}.`;throw new TypeError(s)}}function mn(r,e,...s){switch(e){case"HS256":case"HS384":case"HS512":{if(!Ze(r.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Ot(r.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Ze(r.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Ot(r.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Ze(r.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Ot(r.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(r.algorithm.name!=="Ed25519"&&r.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!Ze(r.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Ze(r.algorithm,"ECDSA"))throw we("ECDSA");const t=gn(e);if(r.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}xn(r,s)}function Ss(r,e,...s){var t;if(s=s.filter(Boolean),s.length>2){const n=s.pop();r+=`one of type ${s.join(", ")}, or ${n}.`}else s.length===2?r+=`one of type ${s[0]} or ${s[1]}.`:r+=`of type ${s[0]}.`;return e==null?r+=` Received ${e}`:typeof e=="function"&&e.name?r+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(r+=` Received an instance of ${e.constructor.name}`),r}const vs=(r,...e)=>Ss("Key must be ",r,...e);function Es(r,e,...s){return Ss(`Key for the ${r} algorithm must be `,e,...s)}const As=r=>xs(r)?!0:(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",ct=["CryptoKey"],wn=(...r)=>{const e=r.filter(Boolean);if(e.length===0||e.length===1)return!0;let s;for(const t of e){const n=Object.keys(t);if(!s||s.size===0){s=new Set(n);continue}for(const i of n){if(s.has(i))return!1;s.add(i)}}return!0};function yn(r){return typeof r=="object"&&r!==null}function ve(r){if(!yn(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const bn=(r,e)=>{if(r.startsWith("RS")||r.startsWith("PS")){const{modulusLength:s}=e.algorithm;if(typeof s!="number"||s<2048)throw new TypeError(`${r} requires key modulusLength to be 2048 bits or larger`)}};function He(r){return ve(r)&&typeof r.kty=="string"}function Sn(r){return r.kty!=="oct"&&typeof r.d=="string"}function vn(r){return r.kty!=="oct"&&typeof r.d>"u"}function En(r){return He(r)&&r.kty==="oct"&&typeof r.k=="string"}function An(r){let e,s;switch(r.kty){case"RSA":{switch(r.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${r.alg.slice(-3)}`},s=r.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(r.alg.slice(-3),10)||1}`},s=r.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(r.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},s=r.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},s=r.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(r.alg){case"Ed25519":e={name:"Ed25519"},s=r.d?["sign"]:["verify"];break;case"EdDSA":e={name:r.crv},s=r.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:r.crv},s=r.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new xe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:s}}const Is=async r=>{if(!r.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:s}=An(r),t=[e,r.ext??!1,r.key_ops??s],n={...r};return delete n.alg,delete n.use,It.subtle.importKey("jwk",n,...t)},Ts=r=>Re(r);let Be,Fe;const Rs=r=>(r==null?void 0:r[Symbol.toStringTag])==="KeyObject",lt=async(r,e,s,t,n=!1)=>{let i=r.get(e);if(i!=null&&i[t])return i[t];const o=await Is({...s,alg:t});return n&&Object.freeze(e),i?i[t]=o:r.set(e,{[t]:o}),o},In={normalizePublicKey:(r,e)=>{if(Rs(r)){let s=r.export({format:"jwk"});return delete s.d,delete s.dp,delete s.dq,delete s.p,delete s.q,delete s.qi,s.k?Ts(s.k):(Fe||(Fe=new WeakMap),lt(Fe,r,s,e))}return He(r)?r.k?Re(r.k):(Fe||(Fe=new WeakMap),lt(Fe,r,r,e,!0)):r},normalizePrivateKey:(r,e)=>{if(Rs(r)){let s=r.export({format:"jwk"});return s.k?Ts(s.k):(Be||(Be=new WeakMap),lt(Be,r,s,e))}return He(r)?r.k?Re(r.k):(Be||(Be=new WeakMap),lt(Be,r,r,e,!0)):r}};async function ks(r,e){if(!ve(r))throw new TypeError("JWK must be an object");switch(e||(e=r.alg),r.kty){case"oct":if(typeof r.k!="string"||!r.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(r.k);case"RSA":if("oth"in r&&r.oth!==void 0)throw new xe('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return Is({...r,alg:e});default:throw new xe('Unsupported "kty" (Key Type) Parameter value')}}const Ke=r=>r==null?void 0:r[Symbol.toStringTag],Pt=(r,e,s)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,s))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${s}`);if(e.alg!==void 0&&e.alg!==r)throw new TypeError(`Invalid key for this operation, when present its alg must be ${r}`);return!0},Tn=(r,e,s,t)=>{if(!(e instanceof Uint8Array)){if(t&&He(e)){if(En(e)&&Pt(r,e,s))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!As(e))throw new TypeError(Es(r,e,...ct,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Ke(e)} instances for symmetric algorithms must be of type "secret"`)}},Rn=(r,e,s,t)=>{if(t&&He(e))switch(s){case"sign":if(Sn(e)&&Pt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(vn(e)&&Pt(r,e,s))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!As(e))throw new TypeError(Es(r,e,...ct,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Ke(e)} instances for asymmetric algorithms must not be of type "secret"`);if(s==="sign"&&e.type==="public")throw new TypeError(`${Ke(e)} instances for asymmetric algorithm signing must be of type "private"`);if(s==="decrypt"&&e.type==="public")throw new TypeError(`${Ke(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&s==="verify"&&e.type==="private")throw new TypeError(`${Ke(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&s==="encrypt"&&e.type==="private")throw new TypeError(`${Ke(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Os(r,e,s,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Tn(e,s,t,r):Rn(e,s,t,r)}Os.bind(void 0,!1);const Ps=Os.bind(void 0,!0);function kn(r,e,s,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new r('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new r('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;s!==void 0?i=new Map([...Object.entries(s),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new xe(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new r(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new r(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const On=(r,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(s=>typeof s!="string")))throw new TypeError(`"${r}" option must be an array of strings`);if(e)return new Set(e)};function Pn(r,e){const s=`SHA-${r.slice(-3)}`;switch(r){case"HS256":case"HS384":case"HS512":return{hash:s,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:s,name:"RSA-PSS",saltLength:r.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:s,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:s,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new xe(`alg ${r} is not supported either by JOSE or your javascript runtime`)}}async function Cn(r,e,s){if(e=await In.normalizePublicKey(e,r),xs(e))return mn(e,r,s),e;if(e instanceof Uint8Array){if(!r.startsWith("HS"))throw new TypeError(vs(e,...ct));return It.subtle.importKey("raw",e,{hash:`SHA-${r.slice(-3)}`,name:"HMAC"},!1,[s])}throw new TypeError(vs(e,...ct,"Uint8Array","JSON Web Key"))}const Nn=async(r,e,s,t)=>{const n=await Cn(r,e,"verify");bn(r,n);const i=Pn(r,n.algorithm);try{return await It.subtle.verify(i,n,s,t)}catch{return!1}};async function Ln(r,e,s){if(!ve(r))throw new Z("Flattened JWS must be an object");if(r.protected===void 0&&r.header===void 0)throw new Z('Flattened JWS must have either of the "protected" or "header" members');if(r.protected!==void 0&&typeof r.protected!="string")throw new Z("JWS Protected Header incorrect type");if(r.payload===void 0)throw new Z("JWS Payload missing");if(typeof r.signature!="string")throw new Z("JWS Signature missing or incorrect type");if(r.header!==void 0&&!ve(r.header))throw new Z("JWS Unprotected Header incorrect type");let t={};if(r.protected)try{const S=Re(r.protected);t=JSON.parse(Xe.decode(S))}catch{throw new Z("JWS Protected Header is invalid")}if(!wn(t,r.header))throw new Z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...r.header},i=kn(Z,new Map([["b64",!0]]),s==null?void 0:s.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Z('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=s&&On("algorithms",s.algorithms);if(c&&!c.has(a))throw new ms('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof r.payload!="string")throw new Z("JWS Payload must be a string")}else if(typeof r.payload!="string"&&!(r.payload instanceof Uint8Array))throw new Z("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,r),l=!0,Ps(a,e,"verify"),He(e)&&(e=await ks(e,a))):Ps(a,e,"verify");const d=un(at.encode(r.protected??""),at.encode("."),typeof r.payload=="string"?at.encode(r.payload):r.payload);let f;try{f=Re(r.signature)}catch{throw new Z("Failed to base64url decode the signature")}if(!await Nn(a,e,f,d))throw new bs;let p;if(o)try{p=Re(r.payload)}catch{throw new Z("Failed to base64url decode the payload")}else typeof r.payload=="string"?p=at.encode(r.payload):p=r.payload;const x={payload:p};return r.protected!==void 0&&(x.protectedHeader=t),r.header!==void 0&&(x.unprotectedHeader=r.header),l?{...x,key:e}:x}async function Dn(r,e,s){if(r instanceof Uint8Array&&(r=Xe.decode(r)),typeof r!="string")throw new Z("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=r.split(".");if(o!==3)throw new Z("Invalid Compact JWS");const a=await Ln({payload:n,protected:t,signature:i},e,s),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Mn=r=>Math.floor(r.getTime()/1e3),Cs=60,Ns=Cs*60,Ct=Ns*24,$n=Ct*7,Wn=Ct*365.25,Un=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ls=r=>{const e=Un.exec(r);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const s=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(s);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(s*Cs);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(s*Ns);break;case"day":case"days":case"d":n=Math.round(s*Ct);break;case"week":case"weeks":case"w":n=Math.round(s*$n);break;default:n=Math.round(s*Wn);break}return e[1]==="-"||e[4]==="ago"?-n:n},Ds=r=>r.toLowerCase().replace(/^application\//,""),Hn=(r,e)=>typeof r=="string"?e.includes(r):Array.isArray(r)?e.some(Set.prototype.has.bind(new Set(r))):!1,Bn=(r,e,s={})=>{let t;try{t=JSON.parse(Xe.decode(e))}catch{}if(!ve(t))throw new me("JWT Claims Set must be a top-level JSON object");const{typ:n}=s;if(n&&(typeof r.typ!="string"||Ds(r.typ)!==Ds(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=s,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),o!==void 0&&d.push("iss");for(const x of new Set(d.reverse()))if(!(x in t))throw new he(`missing required "${x}" claim`,t,x,"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&&!Hn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let f;switch(typeof s.clockTolerance){case"string":f=Ls(s.clockTolerance);break;case"number":f=s.clockTolerance;break;case"undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:_}=s,p=Mn(_||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+f)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-f)throw new Tt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const x=p-t.iat,S=typeof l=="number"?l:Ls(l);if(x-f>S)throw new Tt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(x<0-f)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function Fn(r,e,s){var o;const t=await Dn(r,e,s);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new me("JWTs MUST NOT use unencoded payload");const i={payload:Bn(t.protectedHeader,t.payload,s),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Kn(r){switch(typeof r=="string"&&r.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new xe('Unsupported "alg" value for a JSON Web Key Set')}}function Gn(r){return r&&typeof r=="object"&&Array.isArray(r.keys)&&r.keys.every(qn)}function qn(r){return ve(r)}function Ms(r){return typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}class Jn{constructor(e){if(this._cached=new WeakMap,!Gn(e))throw new Rt("JSON Web Key Set malformed");this._jwks=Ms(e)}async getKey(e,s){const{alg:t,kid:n}={...e,...s==null?void 0:s.header},i=Kn(t),o=this._jwks.keys.filter(l=>{let d=i===l.kty;if(d&&typeof n=="string"&&(d=n===l.kid),d&&typeof l.alg=="string"&&(d=t===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(t){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":d=l.crv==="Ed25519";break;case"EdDSA":d=l.crv==="Ed25519"||l.crv==="Ed448";break}return d}),{0:a,length:c}=o;if(c===0)throw new kt;if(c!==1){const l=new ws,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const f of o)try{yield await $s(d,f,t)}catch{}},l}return $s(this._cached,a,t)}}async function $s(r,e,s){const t=r.get(e)||r.set(e,{}).get(e);if(t[s]===void 0){const n=await ks({...e,ext:!0},s);if(n instanceof Uint8Array||n.type!=="public")throw new Rt("JSON Web Key Set members must be public keys");t[s]=n}return t[s]}function Ws(r){const e=new Jn(r),s=async(t,n)=>e.getKey(t,n);return Object.defineProperties(s,{jwks:{value:()=>Ms(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),s}const Vn=async(r,e,s)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(r.href,{signal:t?t.signal:void 0,redirect:"manual",headers:s.headers}).catch(a=>{throw i?new ys:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new ee("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new ee("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function zn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let Nt;(typeof navigator>"u"||!((Ur=(bt=navigator.userAgent)==null?void 0:bt.startsWith)!=null&&Ur.call(bt,"Mozilla/5.0 ")))&&(Nt="jose/v5.10.0");const Lt=Symbol();function Yn(r,e){return!(typeof r!="object"||r===null||!("uat"in r)||typeof r.uat!="number"||Date.now()-r.uat>=e||!("jwks"in r)||!ve(r.jwks)||!Array.isArray(r.jwks.keys)||!Array.prototype.every.call(r.jwks.keys,ve))}class jn{constructor(e,s){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:s==null?void 0:s.agent,headers:s==null?void 0:s.headers},this._timeoutDuration=typeof(s==null?void 0:s.timeoutDuration)=="number"?s==null?void 0:s.timeoutDuration:5e3,this._cooldownDuration=typeof(s==null?void 0:s.cooldownDuration)=="number"?s==null?void 0:s.cooldownDuration:3e4,this._cacheMaxAge=typeof(s==null?void 0:s.cacheMaxAge)=="number"?s==null?void 0:s.cacheMaxAge:6e5,(s==null?void 0:s[Lt])!==void 0&&(this._cache=s==null?void 0:s[Lt],Yn(s==null?void 0:s[Lt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Ws(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,s){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,s)}catch(t){if(t instanceof kt&&this.coolingDown()===!1)return await this.reload(),this._local(e,s);throw t}}async reload(){this._pendingFetch&&zn()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);Nt&&!e.has("User-Agent")&&(e.set("User-Agent",Nt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Vn(this._url,this._timeoutDuration,this._options).then(s=>{this._local=Ws(s),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=s),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(s=>{throw this._pendingFetch=void 0,s})),await this._pendingFetch}}function Xn(r,e){const s=new jn(r,e),t=async(n,i)=>s.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>s.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>s.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>s.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!s._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=s._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Zn=Re;function Qn(r){if(typeof r!="string")throw new me("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new me("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new me("Invalid JWT");if(!e)throw new me("JWTs must contain a payload");let t;try{t=Zn(e)}catch{throw new me("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Xe.decode(t))}catch{throw new me("Failed to parse the decoded payload as JSON")}if(!ve(n))throw new me("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Dt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function Ee(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function q(r,e,s=""){const t=Dt(r),n=r==null?void 0:r.length,i=e!==void 0;if(!t||i&&n!==e){const o=s&&`"${s}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return r}function Us(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ee(r.outputLen),Ee(r.blockLen)}function Ge(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function Hs(r,e){q(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function ei(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function qe(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Mt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ye(r,e){return r<<32-e|r>>>e}const ti=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function si(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function ri(r){for(let e=0;e<r.length;e++)r[e]=si(r[e]);return r}const Bs=ti?r=>r:ri,Fs=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ni=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Qe(r){if(q(r),Fs)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=ni[r[s]];return e}const Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ks(r){if(r>=Ae._0&&r<=Ae._9)return r-Ae._0;if(r>=Ae.A&&r<=Ae.F)return r-(Ae.A-10);if(r>=Ae.a&&r<=Ae.f)return r-(Ae.a-10)}function dt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Fs)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,i=0;n<s;n++,i+=2){const o=Ks(r.charCodeAt(i)),a=Ks(r.charCodeAt(i+1));if(o===void 0||a===void 0){const c=r[i]+r[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function ke(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];q(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const i=r[t];s.set(i,n),n+=i.length}return s}function Gs(r,e={}){const s=(n,i)=>r(i).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function qs(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const ii=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function oi(r,e,s){return r&e^~r&s}function ai(r,e,s){return r&e^r&s^e&s}class ci{constructor(e,s,t,n){P(this,"blockLen");P(this,"outputLen");P(this,"padOffset");P(this,"isLE");P(this,"buffer");P(this,"view");P(this,"finished",!1);P(this,"length",0);P(this,"pos",0);P(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Mt(this.buffer)}update(e){Ge(this),q(e);const{view:s,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Mt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ge(this),Hs(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;s[o++]=128,qe(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)s[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Mt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,d[f],i)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Oe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ut=BigInt(2**32-1),Js=BigInt(32);function li(r,e=!1){return e?{h:Number(r&ut),l:Number(r>>Js&ut)}:{h:Number(r>>Js&ut)|0,l:Number(r&ut)|0}}function di(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let i=0;i<s;i++){const{h:o,l:a}=li(r[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const ui=(r,e,s)=>r<<s|e>>>32-s,hi=(r,e,s)=>e<<s|r>>>32-s,pi=(r,e,s)=>e<<s-32|r>>>64-s,fi=(r,e,s)=>r<<s-32|e>>>64-s,_i=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pe=new Uint32Array(64);class gi extends ci{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,s,t,n,i,o,a,c]}set(e,s,t,n,i,o,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,s){for(let f=0;f<16;f++,s+=4)Pe[f]=e.getUint32(s,!1);for(let f=16;f<64;f++){const _=Pe[f-15],p=Pe[f-2],x=ye(_,7)^ye(_,18)^_>>>3,S=ye(p,17)^ye(p,19)^p>>>10;Pe[f]=S+Pe[f-7]+x+Pe[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let f=0;f<64;f++){const _=ye(a,6)^ye(a,11)^ye(a,25),p=d+_+oi(a,c,l)+_i[f]+Pe[f]|0,S=(ye(t,2)^ye(t,13)^ye(t,22))+ai(t,n,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=n,n=t,t=p+S|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,i,o,a,c,l,d)}roundClean(){qe(Pe)}destroy(){this.set(0,0,0,0,0,0,0,0),qe(this.buffer)}}class xi extends gi{constructor(){super(32);P(this,"A",Oe[0]|0);P(this,"B",Oe[1]|0);P(this,"C",Oe[2]|0);P(this,"D",Oe[3]|0);P(this,"E",Oe[4]|0);P(this,"F",Oe[5]|0);P(this,"G",Oe[6]|0);P(this,"H",Oe[7]|0)}}const mi=Gs(()=>new xi,ii(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $t=BigInt(0),Wt=BigInt(1);function ht(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function Vs(r){if(typeof r=="bigint"){if(!_t(r))throw new Error("positive bigint expected, got "+r)}else Ee(r);return r}function pt(r){const e=Vs(r).toString(16);return e.length&1?"0"+e:e}function zs(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?$t:BigInt("0x"+r)}function ft(r){return zs(Qe(r))}function Ys(r){return zs(Qe(wi(q(r)).reverse()))}function Ut(r,e){Ee(e),r=Vs(r);const s=dt(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function js(r,e){return Ut(r,e).reverse()}function wi(r){return Uint8Array.from(r)}const _t=r=>typeof r=="bigint"&&$t<=r;function yi(r,e,s){return _t(r)&&_t(e)&&_t(s)&&e<=r&&r<s}function bi(r,e,s,t){if(!yi(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Si(r){let e;for(e=0;r>$t;r>>=Wt,e+=1);return e}const Ht=r=>(Wt<<BigInt(r))-Wt;function vi(r,e,s){if(Ee(r,"hashLen"),Ee(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=E=>new Uint8Array(E),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const f=()=>{c.fill(1),l.fill(0),d=0},_=(...E)=>s(l,ke(c,...E)),p=(E=n)=>{l=_(i,E),c=_(),E.length!==0&&(l=_(o,E),c=_())},x=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let E=0;const I=[];for(;E<e;){c=_();const k=c.slice();I.push(k),E+=c.length}return ke(...I)};return(E,I)=>{f(),p(E);let k;for(;!(k=I(x()));)p();return f(),k}}function Bt(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(i,o,a){const c=r[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(s,!0)}function Xs(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const i=r(s,...t);return e.set(s,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),ne=BigInt(1),Le=BigInt(2),Zs=BigInt(3),Qs=BigInt(4),er=BigInt(5),Ei=BigInt(7),tr=BigInt(8),Ai=BigInt(9),sr=BigInt(16);function pe(r,e){const s=r%e;return s>=ae?s:e+s}function ue(r,e,s){let t=r;for(;e-- >ae;)t*=t,t%=s;return t}function rr(r,e){if(r===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let s=pe(r,e),t=e,n=ae,i=ne;for(;s!==ae;){const a=t/s,c=t%s,l=n-i*a;t=s,s=c,n=i,i=l}if(t!==ne)throw new Error("invert: does not exist");return pe(n,e)}function Ft(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function nr(r,e){const s=(r.ORDER+ne)/Qs,t=r.pow(e,s);return Ft(r,t,e),t}function Ii(r,e){const s=(r.ORDER-er)/tr,t=r.mul(e,Le),n=r.pow(t,s),i=r.mul(e,n),o=r.mul(r.mul(i,Le),n),a=r.mul(i,r.sub(o,r.ONE));return Ft(r,a,e),a}function Ti(r){const e=gt(r),s=ir(r),t=s(e,e.neg(e.ONE)),n=s(e,t),i=s(e,e.neg(t)),o=(r+Ei)/sr;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,t);const f=a.mul(l,n),_=a.mul(l,i),p=a.eql(a.sqr(d),c),x=a.eql(a.sqr(f),c);l=a.cmov(l,d,p),d=a.cmov(_,f,x);const S=a.eql(a.sqr(d),c),E=a.cmov(l,d,S);return Ft(a,E,c),E}}function ir(r){if(r<Zs)throw new Error("sqrt is not defined for small field");let e=r-ne,s=0;for(;e%Le===ae;)e/=Le,s++;let t=Le;const n=gt(r);for(;ar(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return nr;let i=n.pow(t,e);const o=(e+ne)/Le;return function(c,l){if(c.is0(l))return l;if(ar(c,l)!==1)throw new Error("Cannot find square root");let d=s,f=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 x=1,S=c.sqr(_);for(;!c.eql(S,c.ONE);)if(x++,S=c.sqr(S),x===d)throw new Error("Cannot find square root");const E=ne<<BigInt(d-x-1),I=c.pow(f,E);d=x,f=c.sqr(I),_=c.mul(_,f),p=c.mul(p,I)}return p}}function Ri(r){return r%Qs===Zs?nr:r%tr===er?Ii:r%sr===Ai?Ti(r):ir(r)}const ki=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Oi(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=ki.reduce((t,n)=>(t[n]="function",t),e);return Bt(r,s),r}function Pi(r,e,s){if(s<ae)throw new Error("invalid exponent, negatives unsupported");if(s===ae)return r.ONE;if(s===ne)return e;let t=r.ONE,n=e;for(;s>ae;)s&ne&&(t=r.mul(t,n)),n=r.sqr(n),s>>=ne;return t}function or(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((o,a,c)=>r.is0(a)?o:(t[c]=o,r.mul(o,a)),r.ONE),i=r.inv(n);return e.reduceRight((o,a,c)=>r.is0(a)?o:(t[c]=r.mul(o,t[c]),r.mul(o,a)),i),t}function ar(r,e){const s=(r.ORDER-ne)/Le,t=r.pow(e,s),n=r.eql(t,r.ONE),i=r.eql(t,r.ZERO),o=r.eql(t,r.neg(r.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Ci(r,e){e!==void 0&&Ee(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ni{constructor(e,s={}){P(this,"ORDER");P(this,"BITS");P(this,"BYTES");P(this,"isLE");P(this,"ZERO",ae);P(this,"ONE",ne);P(this,"_lengths");P(this,"_sqrt");P(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(o=s.allowedLengths)==null?void 0:o.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:i}=Ci(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 pe(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&ne)===ne}neg(e){return pe(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return pe(e*e,this.ORDER)}add(e,s){return pe(e+s,this.ORDER)}sub(e,s){return pe(e-s,this.ORDER)}mul(e,s){return pe(e*s,this.ORDER)}pow(e,s){return Pi(this,e,s)}div(e,s){return pe(e*rr(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return rr(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Ri(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?js(e,this.BYTES):Ut(e,this.BYTES)}fromBytes(e,s=!1){q(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?Ys(e):ft(e);if(a&&(c=pe(c,o)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return or(this,e)}cmov(e,s,t){return t?s:e}}function gt(r,e={}){return new Ni(r,e)}function cr(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function lr(r){const e=cr(r);return e+Math.ceil(e/2)}function Li(r,e,s=!1){q(r);const t=r.length,n=cr(e),i=lr(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=s?Ys(r):ft(r),a=pe(o,e-ne)+ne;return s?js(a,n):Ut(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Je=BigInt(0),De=BigInt(1);function xt(r,e){const s=e.negate();return r?s:e}function dr(r,e){const s=or(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function ur(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function Kt(r,e){ur(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,i=Ht(r),o=BigInt(r);return{windows:s,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function hr(r,e,s){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=s;let a=Number(r&n),c=r>>o;a>t&&(a-=i,c+=De);const l=e*t,d=l+Math.abs(a)-1,f=a===0,_=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:_,isNegF:p,offsetF:l}}const Gt=new WeakMap,pr=new WeakMap;function qt(r){return pr.get(r)||1}function fr(r){if(r!==Je)throw new Error("invalid wNAF")}class Di{constructor(e,s){P(this,"BASE");P(this,"ZERO");P(this,"Fn");P(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Je;)s&De&&(t=t.add(n)),n=n.double(),s>>=De;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=Kt(s,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Kt(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:f,isNegF:_,offsetF:p}=hr(t,a,o);t=c,d?i=i.add(xt(_,s[p])):n=n.add(xt(f,s[l]))}return fr(t),{p:n,f:i}}wNAFUnsafe(e,s,t,n=this.ZERO){const i=Kt(e,this.bits);for(let o=0;o<i.windows&&t!==Je;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=hr(t,o,i);if(t=a,!l){const f=s[c];n=n.add(d?f.negate():f)}}return fr(t),n}getPrecomputes(e,s,t){let n=Gt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),Gt.set(s,n))),n}cached(e,s,t){const n=qt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const i=qt(e);return i===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),s,n)}createCache(e,s){ur(s,this.bits),pr.set(e,s),Gt.delete(e)}hasCache(e){return qt(e)!==1}}function Mi(r,e,s,t){let n=e,i=r.ZERO,o=r.ZERO;for(;s>Je||t>Je;)s&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),s>>=De,t>>=De;return{p1:i,p2:o}}function _r(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Oi(e),e}else return gt(r,{isLE:s})}function $i(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Je))throw new Error(`CURVE.${c} must be positive bigint`)}const n=_r(e.p,s.Fp,t),i=_r(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Wi(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class gr{constructor(e,s){P(this,"oHash");P(this,"iHash");P(this,"blockLen");P(this,"outputLen");P(this,"finished",!1);P(this,"destroyed",!1);if(Us(e),q(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),qe(n)}update(e){return Ge(this),this.iHash.update(e),this}digestInto(e){Ge(this),q(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const xr=(r,e,s)=>new gr(r,e).update(s).digest();xr.create=(r,e)=>new gr(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const mr=(r,e)=>(r+(r>=0?e:-e)/wr)/e;function Ui(r,e,s){const[[t,n],[i,o]]=e,a=mr(o*r,s),c=mr(-n*r,s);let l=r-a*t-c*i,d=-a*n-c*o;const f=l<Ie,_=d<Ie;f&&(l=-l),_&&(d=-d);const p=Ht(Math.ceil(Si(s)/2))+Ve;if(l<Ie||l>=p||d<Ie||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:f,k1:l,k2neg:_,k2:d}}function Jt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function Vt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ht(s.lowS,"lowS"),ht(s.prehash,"prehash"),s.format!==void 0&&Jt(s.format),s}class Hi extends Error{constructor(e=""){super(e)}}const Ce={Err:Hi,_tlv:{encode:(r,e)=>{const{Err:s}=Ce;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=pt(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const i=t>127?pt(n.length/2|128):"";return pt(r)+i+n+e},decode(r,e){const{Err:s}=Ce;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(t+=c,o<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(r){const{Err:e}=Ce;if(r<Ie)throw new e("integer: negative integers are not allowed");let s=pt(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=Ce;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ft(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=Ce,n=q(r,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=Ce,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Ve=BigInt(1),wr=BigInt(2),mt=BigInt(3),Bi=BigInt(4);function Fi(r,e={}){const s=$i("weierstrass",r,e),{Fp:t,Fn:n}=s;let i=s.CURVE;const{h:o,n:a}=i;Bt(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=br(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(M,m,w){const{x:T,y:O}=m.toAffine(),D=t.toBytes(T);if(ht(w,"isCompressed"),w){d();const y=!t.isOdd(O);return ke(yr(y),D)}else return ke(Uint8Array.of(4),D,t.toBytes(O))}function _(M){q(M,void 0,"Point");const{publicKey:m,publicKeyUncompressed:w}=l,T=M.length,O=M[0],D=M.subarray(1);if(T===m&&(O===2||O===3)){const y=t.fromBytes(D);if(!t.isValid(y))throw new Error("bad point: is not on curve, wrong x");const b=S(y);let v;try{v=t.sqrt(b)}catch(H){const W=H instanceof Error?": "+H.message:"";throw new Error("bad point: is not on curve, sqrt error"+W)}d();const A=t.isOdd(v);return(O&1)===1!==A&&(v=t.neg(v)),{x:y,y:v}}else if(T===w&&O===4){const y=t.BYTES,b=t.fromBytes(D.subarray(0,y)),v=t.fromBytes(D.subarray(y,y*2));if(!E(b,v))throw new Error("bad point: is not on curve");return{x:b,y:v}}else throw new Error(`bad point: got length ${T}, expected compressed=${m} or uncompressed=${w}`)}const p=e.toBytes||f,x=e.fromBytes||_;function S(M){const m=t.sqr(M),w=t.mul(m,M);return t.add(t.add(w,t.mul(M,i.a)),i.b)}function E(M,m){const w=t.sqr(m),T=S(M);return t.eql(w,T)}if(!E(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(i.a,mt),Bi),k=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(I,k)))throw new Error("bad curve params: a or b");function B(M,m,w=!1){if(!t.isValid(m)||w&&t.is0(m))throw new Error(`bad point coordinate ${M}`);return m}function $(M){if(!(M instanceof X))throw new Error("Weierstrass Point expected")}function J(M){if(!c||!c.basises)throw new Error("no endo");return Ui(M,c.basises,n.ORDER)}const G=Xs((M,m)=>{const{X:w,Y:T,Z:O}=M;if(t.eql(O,t.ONE))return{x:w,y:T};const D=M.is0();m==null&&(m=D?t.ONE:t.inv(O));const y=t.mul(w,m),b=t.mul(T,m),v=t.mul(O,m);if(D)return{x:t.ZERO,y:t.ZERO};if(!t.eql(v,t.ONE))throw new Error("invZ was invalid");return{x:y,y:b}}),se=Xs(M=>{if(M.is0()){if(e.allowInfinityPoint&&!t.is0(M.Y))return;throw new Error("bad point: ZERO")}const{x:m,y:w}=M.toAffine();if(!t.isValid(m)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!E(m,w))throw new Error("bad point: equation left != right");if(!M.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(M,m,w,T,O){return w=new X(t.mul(w.X,M),w.Y,w.Z),m=xt(T,m),w=xt(O,w),m.add(w)}const N=class N{constructor(m,w,T){P(this,"X");P(this,"Y");P(this,"Z");this.X=B("x",m),this.Y=B("y",w,!0),this.Z=B("z",T),Object.freeze(this)}static CURVE(){return i}static fromAffine(m){const{x:w,y:T}=m||{};if(!m||!t.isValid(w)||!t.isValid(T))throw new Error("invalid affine point");if(m instanceof N)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(T)?N.ZERO:new N(w,T,t.ONE)}static fromBytes(m){const w=N.fromAffine(x(q(m,void 0,"point")));return w.assertValidity(),w}static fromHex(m){return N.fromBytes(dt(m))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(m=8,w=!0){return U.createCache(this,m),w||this.multiply(mt),this}assertValidity(){se(this)}hasEvenY(){const{y:m}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(m)}equals(m){$(m);const{X:w,Y:T,Z:O}=this,{X:D,Y:y,Z:b}=m,v=t.eql(t.mul(w,b),t.mul(D,O)),A=t.eql(t.mul(T,b),t.mul(y,O));return v&&A}negate(){return new N(this.X,t.neg(this.Y),this.Z)}double(){const{a:m,b:w}=i,T=t.mul(w,mt),{X:O,Y:D,Z:y}=this;let b=t.ZERO,v=t.ZERO,A=t.ZERO,R=t.mul(O,O),H=t.mul(D,D),W=t.mul(y,y),L=t.mul(O,D);return L=t.add(L,L),A=t.mul(O,y),A=t.add(A,A),b=t.mul(m,A),v=t.mul(T,W),v=t.add(b,v),b=t.sub(H,v),v=t.add(H,v),v=t.mul(b,v),b=t.mul(L,b),A=t.mul(T,A),W=t.mul(m,W),L=t.sub(R,W),L=t.mul(m,L),L=t.add(L,A),A=t.add(R,R),R=t.add(A,R),R=t.add(R,W),R=t.mul(R,L),v=t.add(v,R),W=t.mul(D,y),W=t.add(W,W),R=t.mul(W,L),b=t.sub(b,R),A=t.mul(W,H),A=t.add(A,A),A=t.add(A,A),new N(b,v,A)}add(m){$(m);const{X:w,Y:T,Z:O}=this,{X:D,Y:y,Z:b}=m;let v=t.ZERO,A=t.ZERO,R=t.ZERO;const H=i.a,W=t.mul(i.b,mt);let L=t.mul(w,D),K=t.mul(T,y),j=t.mul(O,b),de=t.add(w,T),V=t.add(D,y);de=t.mul(de,V),V=t.add(L,K),de=t.sub(de,V),V=t.add(w,O);let oe=t.add(D,b);return V=t.mul(V,oe),oe=t.add(L,j),V=t.sub(V,oe),oe=t.add(T,O),v=t.add(y,b),oe=t.mul(oe,v),v=t.add(K,j),oe=t.sub(oe,v),R=t.mul(H,V),v=t.mul(W,j),R=t.add(v,R),v=t.sub(K,R),R=t.add(K,R),A=t.mul(v,R),K=t.add(L,L),K=t.add(K,L),j=t.mul(H,j),V=t.mul(W,V),K=t.add(K,j),j=t.sub(L,j),j=t.mul(H,j),V=t.add(V,j),L=t.mul(K,V),A=t.add(A,L),L=t.mul(oe,V),v=t.mul(de,v),v=t.sub(v,L),L=t.mul(de,K),R=t.mul(oe,R),R=t.add(R,L),new N(v,A,R)}subtract(m){return this.add(m.negate())}is0(){return this.equals(N.ZERO)}multiply(m){const{endo:w}=e;if(!n.isValidNot0(m))throw new Error("invalid scalar: out of range");let T,O;const D=y=>U.cached(this,y,b=>dr(N,b));if(w){const{k1neg:y,k1:b,k2neg:v,k2:A}=J(m),{p:R,f:H}=D(b),{p:W,f:L}=D(A);O=H.add(L),T=F(w.beta,R,W,y,v)}else{const{p:y,f:b}=D(m);T=y,O=b}return dr(N,[T,O])[0]}multiplyUnsafe(m){const{endo:w}=e,T=this;if(!n.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ie||T.is0())return N.ZERO;if(m===Ve)return T;if(U.hasCache(this))return this.multiply(m);if(w){const{k1neg:O,k1:D,k2neg:y,k2:b}=J(m),{p1:v,p2:A}=Mi(N,T,D,b);return F(w.beta,v,A,O,y)}else return U.unsafe(T,m)}toAffine(m){return G(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return o===Ve?!0:m?m(N,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:m}=e;return o===Ve?this:m?m(N,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(m=!0){return ht(m,"isCompressed"),this.assertValidity(),p(N,this,m)}toHex(m=!0){return Qe(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};P(N,"BASE",new N(i.Gx,i.Gy,t.ONE)),P(N,"ZERO",new N(t.ZERO,t.ONE,t.ZERO)),P(N,"Fp",t),P(N,"Fn",n);let X=N;const re=n.BITS,U=new Di(X,e.endo?Math.ceil(re/2):re);return X.BASE.precompute(8),X}function yr(r){return Uint8Array.of(r?2:3)}function br(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Ki(r,e={}){const{Fn:s}=r,t=e.randomBytes||qs,n=Object.assign(br(r.Fp,s),{seed:lr(s.ORDER)});function i(p){try{const x=s.fromBytes(p);return s.isValidNot0(x)}catch{return!1}}function o(p,x){const{publicKey:S,publicKeyUncompressed:E}=n;try{const I=p.length;return x===!0&&I!==S||x===!1&&I!==E?!1:!!r.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Li(q(p,n.seed,"seed"),s.ORDER)}function c(p,x=!0){return r.BASE.multiply(s.fromBytes(p)).toBytes(x)}function l(p){const{secretKey:x,publicKey:S,publicKeyUncompressed:E}=n;if(!Dt(p)||"_lengths"in s&&s._lengths||x===S)return;const I=q(p,void 0,"key").length;return I===S||I===E}function d(p,x,S=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(x)===!1)throw new Error("second arg must be public key");const E=s.fromBytes(p);return r.fromBytes(x).multiply(E).toBytes(S)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},_=Wi(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:_,Point:r,utils:f,lengths:n})}function Gi(r,e,s={}){Us(e),Bt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||qs,n=s.hmac||((m,w)=>xr(e,m,w)),{Fp:i,Fn:o}=r,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:f,utils:_,lengths:p}=Ki(r,s),x={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},S=a*wr<i.ORDER;function E(m){const w=a>>Ve;return m>w}function I(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function k(){if(S)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(m,w){Jt(w);const T=p.signature,O=w==="compact"?T:w==="recovered"?T+1:void 0;return q(m,O)}class ${constructor(w,T,O){P(this,"r");P(this,"s");P(this,"recovery");if(this.r=I("r",w),this.s=I("s",T),O!=null){if(k(),![0,1,2,3].includes(O))throw new Error("invalid recovery id");this.recovery=O}Object.freeze(this)}static fromBytes(w,T=x.format){B(w,T);let O;if(T==="der"){const{r:v,s:A}=Ce.toSig(q(w));return new $(v,A)}T==="recovered"&&(O=w[0],T="compact",w=w.subarray(1));const D=p.signature/2,y=w.subarray(0,D),b=w.subarray(D,D*2);return new $(o.fromBytes(y),o.fromBytes(b),O)}static fromHex(w,T){return this.fromBytes(dt(w),T)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new $(this.r,this.s,w)}recoverPublicKey(w){const{r:T,s:O}=this,D=this.assertRecovery(),y=D===2||D===3?T+a:T;if(!i.isValid(y))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const b=i.toBytes(y),v=r.fromBytes(ke(yr((D&1)===0),b)),A=o.inv(y),R=G(q(w,void 0,"msgHash")),H=o.create(-R*A),W=o.create(O*A),L=r.BASE.multiplyUnsafe(H).add(v.multiplyUnsafe(W));if(L.is0())throw new Error("invalid recovery: point at infinify");return L.assertValidity(),L}hasHighS(){return E(this.s)}toBytes(w=x.format){if(Jt(w),w==="der")return dt(Ce.hexFromSig(this));const{r:T,s:O}=this,D=o.toBytes(T),y=o.toBytes(O);return w==="recovered"?(k(),ke(Uint8Array.of(this.assertRecovery()),D,y)):ke(D,y)}toHex(w){return Qe(this.toBytes(w))}}const J=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const T=ft(w),O=w.length*8-c;return O>0?T>>BigInt(O):T},G=s.bits2int_modN||function(w){return o.create(J(w))},se=Ht(c);function F(m){return bi("num < 2^"+c,m,Ie,se),o.toBytes(m)}function X(m,w){return q(m,void 0,"message"),w?q(e(m),void 0,"prehashed message"):m}function re(m,w,T){const{lowS:O,prehash:D,extraEntropy:y}=Vt(T,x);m=X(m,D);const b=G(m),v=o.fromBytes(w);if(!o.isValidNot0(v))throw new Error("invalid private key");const A=[F(v),F(b)];if(y!=null&&y!==!1){const L=y===!0?t(p.secretKey):y;A.push(q(L,void 0,"extraEntropy"))}const R=ke(...A),H=b;function W(L){const K=J(L);if(!o.isValidNot0(K))return;const j=o.inv(K),de=r.BASE.multiply(K).toAffine(),V=o.create(de.x);if(V===Ie)return;const oe=o.create(j*o.create(H+V*v));if(oe===Ie)return;let Hr=(de.x===V?0:2)|Number(de.y&Ve),Br=oe;return O&&E(oe)&&(Br=o.neg(oe),Hr^=1),new $(V,Br,S?void 0:Hr)}return{seed:R,k2sig:W}}function U(m,w,T={}){const{seed:O,k2sig:D}=re(m,w,T);return vi(e.outputLen,o.BYTES,n)(O,D).toBytes(T.format)}function N(m,w,T,O={}){const{lowS:D,prehash:y,format:b}=Vt(O,x);if(T=q(T,void 0,"publicKey"),w=X(w,y),!Dt(m)){const v=m instanceof $?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+v)}B(m,b);try{const v=$.fromBytes(m,b),A=r.fromBytes(T);if(D&&v.hasHighS())return!1;const{r:R,s:H}=v,W=G(w),L=o.inv(H),K=o.create(W*L),j=o.create(R*L),de=r.BASE.multiplyUnsafe(K).add(A.multiplyUnsafe(j));return de.is0()?!1:o.create(de.x)===R}catch{return!1}}function M(m,w,T={}){const{prehash:O}=Vt(T,x);return w=X(w,O),$.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:f,utils:_,lengths:p,Point:r,sign:U,verify:N,recoverPublicKey:M,Signature:$,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const zt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},qi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Sr=BigInt(2);function Ji(r){const e=zt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,f=ue(d,s,e)*d%e,_=ue(f,s,e)*d%e,p=ue(_,Sr,e)*l%e,x=ue(p,n,e)*p%e,S=ue(x,i,e)*x%e,E=ue(S,a,e)*S%e,I=ue(E,c,e)*E%e,k=ue(I,a,e)*S%e,B=ue(k,s,e)*d%e,$=ue(B,o,e)*x%e,J=ue($,t,e)*l%e,G=ue(J,Sr,e);if(!Yt.eql(Yt.sqr(G),r))throw new Error("Cannot find square root");return G}const Yt=gt(zt.p,{sqrt:Ji}),Vi=Gi(Fi(zt,{Fp:Yt,endo:qi}),mi),zi=BigInt(0),et=BigInt(1),Yi=BigInt(2),ji=BigInt(7),Xi=BigInt(256),Zi=BigInt(113),vr=[],Er=[],Ar=[];for(let r=0,e=et,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],vr.push(2*(5*t+s)),Er.push((r+1)*(r+2)/2%64);let n=zi;for(let i=0;i<7;i++)e=(e<<et^(e>>ji)*Zi)%Xi,e&Yi&&(n^=et<<(et<<BigInt(i))-et);Ar.push(n)}const Ir=di(Ar,!0),Qi=Ir[0],eo=Ir[1],Tr=(r,e,s)=>s>32?pi(r,e,s):ui(r,e,s),Rr=(r,e,s)=>s>32?fi(r,e,s):hi(r,e,s);function to(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)s[o]=r[o]^r[o+10]^r[o+20]^r[o+30]^r[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=s[c],d=s[c+1],f=Tr(l,d,1)^s[a],_=Rr(l,d,1)^s[a+1];for(let p=0;p<50;p+=10)r[o+p]^=f,r[o+p+1]^=_}let n=r[2],i=r[3];for(let o=0;o<24;o++){const a=Er[o],c=Tr(n,i,a),l=Rr(n,i,a),d=vr[o];n=r[d],i=r[d+1],r[d]=c,r[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)s[a]=r[o+a];for(let a=0;a<10;a++)r[o+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=Qi[t],r[1]^=eo[t]}qe(s)}class jt{constructor(e,s,t,n=!1,i=24){P(this,"state");P(this,"pos",0);P(this,"posOut",0);P(this,"finished",!1);P(this,"state32");P(this,"destroyed",!1);P(this,"blockLen");P(this,"suffix");P(this,"outputLen");P(this,"enableXOF",!1);P(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=i,Ee(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ei(this.state)}clone(){return this._cloneInto()}keccak(){Bs(this.state32),to(this.state32,this.rounds),Bs(this.state32),this.posOut=0,this.pos=0}update(e){Ge(this),q(e);const{blockLen:s,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(s-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ge(this,!1),q(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(s.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ee(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Hs(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,qe(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new jt(s,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const kr=((r,e,s,t={})=>Gs(()=>new jt(e,r,s),t))(1,136,32),so=60;class ro{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Xn(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+so<n)return u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await Fn(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};u.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Qn(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
+
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=kr(i),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=no(a),l=c.slice(0,32),d=c.slice(32,64),f=c[64],_=f>=27?f-27:f,S=new Vi.Signature(Or(l),Or(d)).addRecoveryBit(_).recoverPublicKey(o).toBytes(!1).slice(1),E=kr(S);return"0x"+Qe(E.slice(12))}}function no(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function Or(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const io=3e4,oo=1e3;class ao{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,oo*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??io);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const co=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Me{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=Me.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){u.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Me.sha256Hex(s);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Me.generateRandom16Hex(),l=Me.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",f=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const _=window.open(f,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!_){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),$(),t(new Error("Authentication timeout"))},5*60*1e3),x=10,S=30;let E=0,I=null;const k=()=>{clearInterval(B),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+S+"초간 대기합니다"),I=setTimeout(()=>{$(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},S*1e3)},B=setInterval(()=>{E++;try{_.closed&&(E<=x?k():($(),t(new Error("로그인이 취소되었습니다"))))}catch{k()}},1e3),$=()=>{clearTimeout(p),clearInterval(B),I&&clearTimeout(I),window.removeEventListener("message",J)},J=G=>{if(G.origin!==e.expectedOrigin)return;if(!co.has(G.origin)){u.error("[CROSSx] postMessage origin이 허용 목록에 없음:",G.origin),$(),t(new Error("Unauthorized OAuth origin"));return}$();const se=typeof G.data.status=="string",F=se?G.data.data??{}:G.data;u.log("[CROSSx] OAuth postMessage 수신 —",{format:se?"wrapped":"flat",status:se?G.data.status:"(flat)"});const X=(F==null?void 0:F.state)??G.data.state;if(!X||X!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(se&&G.data.status!=="success"){u.error("[CROSSx] OAuth 실패:",F==null?void 0:F.error),t(new Error((F==null?void 0:F.error)||"Authentication failed"));return}if(!se&&(F!=null&&F.error)){u.error("[CROSSx] OAuth 실패:",F.error),t(new Error(F.error||"Authentication failed"));return}const re=F==null?void 0:F.idToken,U=F==null?void 0:F.accessToken,N=U??re,M=(F==null?void 0:F.email)||void 0;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!U,hasIdToken:!!re,hasEmail:!!M}),!N){u.error("[CROSSx] 토큰을 찾을 수 없음:",G.data),t(new Error("Token not found in response"));return}const m={token:N,email:M},w=T=>{Me.verifyIdTokenNonce(T,l).then(()=>s(m)).catch(O=>{u.error("[CROSSx] nonce 검증 실패:",O),t(O instanceof Error?O:new Error("nonce verification failed"))})};U?U.split(".").length===3?w(U):re?w(re):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(m)):re?w(re):t(new Error("Token not found in response"))};window.addEventListener("message",J)})}}const tt="crossx_wallet_data",ze="crossx_mock_pin_hash";class lo{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(tt)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(tt);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(tt,n);const i=(s=this.pinStore)==null?void 0:s.get();return i&&(await this.storage.set(ze,i),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new g(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(tt);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,i,o){return u.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,i,o){return u.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${i} from=${o}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,i){u.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,s,t,n){return u.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(ze);return s&&s!==e?!1:(s||await this.storage.set(ze,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var i;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new g(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(ze);if(n&&t&&n!==t)throw new g(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(ze,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var i;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new g(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new g(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(tt,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(ze,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class $e{constructor(e,s,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(_s))return e;const s=!e||this.tokenStore.isExpiringSoon(_s);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(s)throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return u.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(u.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,s,t,n=!1){var c,l,d,f;const i=await this.ensureValidToken(),o=`${this.baseUrl}${s}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const p=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(p&&typeof p.code=="number"){if(p.code<0||p.code>=400){const x=p.message||p.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:p.code,message:x,url:o,method:e});const S=$e.mapGatewayError(p.code,p.data);if(S===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(u.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(S===h.USER_NOT_FOUND)throw u.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new g(h.USER_NOT_FOUND,$e.getGatewayErrorMessage(p.code,x));const E=S===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:S,I=E===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":$e.getGatewayErrorMessage(p.code,x),k=p.data,B=S===h.PIN_LOCKED?$e.extractLockDetails(k):k??void 0;throw new g(E,I,B)}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:p.code,url:o,method:e}),p.data??p}return p}catch(_){if(_ instanceof g)throw _;const p=((l=_.response)==null?void 0:l.status)??_.status;if((p===401||p===403)&&!n&&this._onTokenRefresh){if(u.warn(`[CROSSx] HTTP ${p} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,s,t,!0);throw new g(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((d=_.response)!=null&&d.data){const x=_.response.data,S=x.message||x.data||"API 요청에 실패했습니다",E=x.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:E,message:S,url:o,method:e,status:(f=_.response)==null?void 0:f.status}),new g(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${E}): ${S}`)}throw _}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new g(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new g(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new g(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new g(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,s,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,o);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,i)).txHash}}async migrateWallet(e,s){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e},t=await this.request("POST","/mnemonic/verify-password",s);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new g(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new g(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new g(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new g(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(s==null?void 0:s.remainingAttempts)??(s==null?void 0:s.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(s==null?void 0:s.maxAttempts)??(s==null?void 0:s.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(s==null?void 0:s.permanent)=="boolean"&&(t.permanent=s.permanent),t}static hasLockInfo(e){const s=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!s||typeof s!="object"?!1:typeof s.remainingAttempts=="number"||typeof s.remaining_attempts=="number"||typeof s.maxAttempts=="number"||typeof s.max_attempts=="number"}static mapGatewayError(e,s){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return $e.hasLockInfo(s)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class st{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=st.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?an:on;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new g(st.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=st.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new g(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(rt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Pr="__crossx-confirm-style",te="__crossx-confirm-overlay",uo={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 Cr(r,e){const s=uo[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const ho=`
|
|
7
7
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
8
8
|
|
|
9
9
|
#${te} {
|
|
@@ -1111,31 +1111,15 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1111
1111
|
white-space: nowrap;
|
|
1112
1112
|
flex-shrink: 0;
|
|
1113
1113
|
}
|
|
1114
|
-
.__crossx-connect-other-
|
|
1114
|
+
.__crossx-connect-other-block {
|
|
1115
1115
|
display: flex;
|
|
1116
|
-
|
|
1117
|
-
align-items: center;
|
|
1116
|
+
flex-direction: column;
|
|
1118
1117
|
width: 100%;
|
|
1119
1118
|
padding: 16px;
|
|
1120
1119
|
background: var(--cx-pill-bg);
|
|
1121
1120
|
border: 1px solid var(--cx-border);
|
|
1122
1121
|
border-radius: 20px;
|
|
1123
|
-
|
|
1124
|
-
appearance: none;
|
|
1125
|
-
-webkit-appearance: none;
|
|
1126
|
-
-webkit-tap-highlight-color: transparent;
|
|
1127
|
-
box-shadow: none;
|
|
1128
|
-
outline: none;
|
|
1129
|
-
}
|
|
1130
|
-
.__crossx-connect-other-btn:hover,
|
|
1131
|
-
.__crossx-connect-other-btn:focus,
|
|
1132
|
-
.__crossx-connect-other-btn:active {
|
|
1133
|
-
opacity: 1 !important;
|
|
1134
|
-
box-shadow: none !important;
|
|
1135
|
-
outline: none !important;
|
|
1136
|
-
filter: none !important;
|
|
1137
|
-
transform: none !important;
|
|
1138
|
-
background: var(--cx-pill-bg) !important;
|
|
1122
|
+
box-sizing: border-box;
|
|
1139
1123
|
}
|
|
1140
1124
|
.__crossx-connect-other-text {
|
|
1141
1125
|
display: flex;
|
|
@@ -1143,8 +1127,57 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1143
1127
|
flex-direction: column;
|
|
1144
1128
|
align-items: flex-start;
|
|
1145
1129
|
justify-content: center;
|
|
1130
|
+
gap: 6px;
|
|
1146
1131
|
min-width: 0;
|
|
1147
1132
|
}
|
|
1133
|
+
.__crossx-connect-other-wallet--inline {
|
|
1134
|
+
display: inline-flex;
|
|
1135
|
+
align-items: center;
|
|
1136
|
+
gap: 6px;
|
|
1137
|
+
vertical-align: middle;
|
|
1138
|
+
margin: 0;
|
|
1139
|
+
padding: 0;
|
|
1140
|
+
background: none;
|
|
1141
|
+
border: none;
|
|
1142
|
+
border-radius: 0;
|
|
1143
|
+
color: inherit;
|
|
1144
|
+
font: inherit;
|
|
1145
|
+
font-size: inherit;
|
|
1146
|
+
font-weight: inherit;
|
|
1147
|
+
line-height: inherit;
|
|
1148
|
+
text-decoration: none;
|
|
1149
|
+
cursor: default;
|
|
1150
|
+
user-select: none;
|
|
1151
|
+
-webkit-user-select: none;
|
|
1152
|
+
-webkit-tap-highlight-color: transparent;
|
|
1153
|
+
box-shadow: none;
|
|
1154
|
+
outline: none;
|
|
1155
|
+
}
|
|
1156
|
+
.__crossx-connect-other-wallet-icon {
|
|
1157
|
+
display: inline-flex;
|
|
1158
|
+
flex-shrink: 0;
|
|
1159
|
+
line-height: 0;
|
|
1160
|
+
}
|
|
1161
|
+
.__crossx-connect-other-wallet-icon svg {
|
|
1162
|
+
display: block;
|
|
1163
|
+
width: 16px;
|
|
1164
|
+
height: 16px;
|
|
1165
|
+
}
|
|
1166
|
+
.__crossx-connect-other-wallet--inline:hover,
|
|
1167
|
+
.__crossx-connect-other-wallet--inline:active {
|
|
1168
|
+
color: inherit;
|
|
1169
|
+
text-decoration: none;
|
|
1170
|
+
opacity: 1;
|
|
1171
|
+
background: none;
|
|
1172
|
+
box-shadow: none;
|
|
1173
|
+
}
|
|
1174
|
+
.__crossx-connect-other-wallet--inline:focus {
|
|
1175
|
+
outline: none;
|
|
1176
|
+
}
|
|
1177
|
+
.__crossx-connect-other-wallet--inline:focus-visible {
|
|
1178
|
+
outline: 1px dotted var(--cx-hint);
|
|
1179
|
+
outline-offset: 2px;
|
|
1180
|
+
}
|
|
1148
1181
|
.__crossx-connect-other-title {
|
|
1149
1182
|
font-size: 18px;
|
|
1150
1183
|
font-weight: 700;
|
|
@@ -1156,12 +1189,14 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1156
1189
|
.__crossx-connect-other-desc {
|
|
1157
1190
|
font-size: 14px;
|
|
1158
1191
|
font-weight: 400;
|
|
1159
|
-
line-height: 1.
|
|
1192
|
+
line-height: 1.45;
|
|
1160
1193
|
color: var(--cx-subtitle);
|
|
1161
1194
|
font-family: 'Pretendard', 'Sora', -apple-system, sans-serif;
|
|
1162
1195
|
text-align: left;
|
|
1163
1196
|
}
|
|
1164
|
-
|
|
1197
|
+
.__crossx-connect-other-summary {
|
|
1198
|
+
margin: 0;
|
|
1199
|
+
}
|
|
1165
1200
|
/* ── Wallet Selector Modal ─────────────────────────────────── */
|
|
1166
1201
|
.__crossx-wallet-list {
|
|
1167
1202
|
display: flex;
|
|
@@ -1998,31 +2033,31 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1998
2033
|
color: var(--cx-title);
|
|
1999
2034
|
margin: 0;
|
|
2000
2035
|
}
|
|
2001
|
-
`;function fe(){let r=document.getElementById(
|
|
2036
|
+
`;function fe(){let r=document.getElementById(Pr);r||(r=document.createElement("style"),r.id=Pr,document.head.appendChild(r)),r.textContent=ho}function _e(r){const e=r.querySelector(".__crossx-card");if(e){const n=(e.getAttribute("style")??"").match(/--cx-bg:\s*([^;]+)/);if(n){const i=n[1].trim();r.style.setProperty("--cx-bg",i);const o=document.createElement("div");o.className="__crossx-safe-area-fill",o.style.background=i,r.appendChild(o)}}const s=t=>t.stopPropagation();for(const t of["pointerdown","pointerup","mousedown","mouseup","click"])r.addEventListener(t,s);r.setAttribute("data-vaul-no-drag","");for(const t of["touchstart","touchend"])r.addEventListener(t,s);r.addEventListener("touchmove",t=>{t.stopPropagation();let n=t.target;for(;n&&n!==r;){const i=window.getComputedStyle(n);if((i.overflowY==="auto"||i.overflowY==="scroll")&&n.scrollHeight>n.clientHeight)return;n=n.parentElement}t.preventDefault()},{passive:!1}),document.body.appendChild(r)}const po=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function Ye(){if(po()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}}function ie(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function fo(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=Xt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Nr={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 Lr(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Nr[e]?Nr[e]:r}function Xt(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,o=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function Zt(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function _o(r){try{return BigInt(r).toLocaleString()}catch{return r}}function go(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=18}=r;if(!e)return null;try{const a=BigInt(e),c=_o(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${Xt(l,o)} ${i}`,maxFeeGwei:Zt(t),maxPriorityFeeGwei:n?Zt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${Xt(l,o)} ${i}`,gasPriceGwei:Zt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Dr(r){const e=go(r);if(!e)return Y("Estimated fee","<span>—</span>");let s=Y("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=Y("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=Y("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=Y("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=Y("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const Te=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
2002
2037
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
2003
2038
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
2004
2039
|
</svg>`,ce=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
2005
2040
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
2006
2041
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
2007
|
-
</svg>`,
|
|
2042
|
+
</svg>`,xo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2008
2043
|
<circle cx="20" cy="20" r="20" fill="#00D5AA"/>
|
|
2009
2044
|
<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"/>
|
|
2010
|
-
</svg>`,
|
|
2045
|
+
</svg>`,mo='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 318.6 318.6" aria-hidden="true"><style>.st1,.st6{fill:#e4761b;stroke:#e4761b;stroke-linecap:round;stroke-linejoin:round}.st6{fill:#f6851b;stroke:#f6851b}</style><path fill="#e2761b" stroke="#e2761b" stroke-linecap="round" stroke-linejoin="round" d="m274.1 35.5-99.5 73.9L193 65.8z"/><path d="m44.4 35.5 98.7 74.6-17.5-44.3zm193.9 171.3-26.5 40.6 56.7 15.6 16.3-55.3zm-204.4.9L50.1 263l56.7-15.6-26.5-40.6z" class="st1"/><path d="m103.6 138.2-15.8 23.9 56.3 2.5-2-60.5zm111.3 0-39-34.8-1.3 61.2 56.2-2.5zM106.8 247.4l33.8-16.5-29.2-22.8zm71.1-16.5 33.9 16.5-4.7-39.3z" class="st1"/><path fill="#d7c1b3" stroke="#d7c1b3" stroke-linecap="round" stroke-linejoin="round" d="m211.8 247.4-33.9-16.5 2.7 22.1-.3 9.3zm-105 0 31.5 14.9-.2-9.3 2.5-22.1z"/><path fill="#233447" stroke="#233447" stroke-linecap="round" stroke-linejoin="round" d="m138.8 193.5-28.2-8.3 19.9-9.1zm40.9 0 8.3-17.4 20 9.1z"/><path fill="#cd6116" stroke="#cd6116" stroke-linecap="round" stroke-linejoin="round" d="m106.8 247.4 4.8-40.6-31.3.9zM207 206.8l4.8 40.6 26.5-39.7zm23.8-44.7-56.2 2.5 5.2 28.9 8.3-17.4 20 9.1zm-120.2 23.1 20-9.1 8.2 17.4 5.3-28.9-56.3-2.5z"/><path fill="#e4751f" stroke="#e4751f" stroke-linecap="round" stroke-linejoin="round" d="m87.8 162.1 23.6 46-.8-22.9zm120.3 23.1-1 22.9 23.7-46zm-64-20.6-5.3 28.9 6.6 34.1 1.5-44.9zm30.5 0-2.7 18 1.2 45 6.7-34.1z"/><path d="m179.8 193.5-6.7 34.1 4.8 3.3 29.2-22.8 1-22.9zm-69.2-8.3.8 22.9 29.2 22.8 4.8-3.3-6.6-34.1z" class="st6"/><path fill="#c0ad9e" stroke="#c0ad9e" stroke-linecap="round" stroke-linejoin="round" d="m180.3 262.3.3-9.3-2.5-2.2h-37.7l-2.3 2.2.2 9.3-31.5-14.9 11 9 22.3 15.5h38.3l22.4-15.5 11-9z"/><path fill="#161616" stroke="#161616" stroke-linecap="round" stroke-linejoin="round" d="m177.9 230.9-4.8-3.3h-27.7l-4.8 3.3-2.5 22.1 2.3-2.2h37.7l2.5 2.2z"/><path fill="#763d16" stroke="#763d16" stroke-linecap="round" stroke-linejoin="round" d="m278.3 114.2 8.5-40.8-12.7-37.9-96.2 71.4 37 31.3 52.3 15.3 11.6-13.5-5-3.6 8-7.3-6.2-4.8 8-6.1zM31.8 73.4l8.5 40.8-5.4 4 8 6.1-6.1 4.8 8 7.3-5 3.6 11.5 13.5 52.3-15.3 37-31.3-96.2-71.4z"/><path d="m267.2 153.5-52.3-15.3 15.9 23.9-23.7 46 31.2-.4h46.5zm-163.6-15.3-52.3 15.3-17.4 54.2h46.4l31.1.4-23.6-46zm71 26.4 3.3-57.7 15.2-41.1h-67.5l15 41.1 3.5 57.7 1.2 18.2.1 44.8h27.7l.2-44.8z" class="st6"/></svg>',wo='<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 126.611 126.611" aria-hidden="true"><polygon fill="#F3BA2F" points="38.171,53.203 62.759,28.616 87.36,53.216 101.667,38.909 62.759,0 23.864,38.896 "/><rect x="3.644" y="53.188" transform="matrix(0.7071 0.7071 -0.7071 0.7071 48.7933 8.8106)" fill="#F3BA2F" width="20.233" height="20.234"/><polygon fill="#F3BA2F" points="38.171,73.408 62.759,97.995 87.359,73.396 101.674,87.695 101.667,87.703 62.759,126.611 23.863,87.716 23.843,87.696 "/><rect x="101.64" y="53.189" transform="matrix(-0.7071 0.7071 -0.7071 -0.7071 235.5457 29.0503)" fill="#F3BA2F" width="20.234" height="20.233"/><polygon fill="#F3BA2F" points="77.271,63.298 77.277,63.298 62.759,48.78 52.03,59.509 52.029,59.509 50.797,60.742 48.254,63.285 48.254,63.285 48.234,63.305 48.254,63.326 62.759,77.831 77.277,63.313 77.284,63.305 "/></svg>',yo='<svg width="16" height="16" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true"><circle cx="20" cy="20" r="20" fill="#00D5AA"/><path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/></svg>',bo={[We.MetaMask]:mo,[We.Binance]:wo,[We.CROSSx]:yo},Qt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
|
2011
2046
|
<rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
|
|
2012
2047
|
<path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
|
|
2013
2048
|
<rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
|
|
2014
|
-
</svg>`,
|
|
2049
|
+
</svg>`,So=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
2015
2050
|
<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)"/>
|
|
2016
|
-
</svg>`,
|
|
2051
|
+
</svg>`,vo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
2017
2052
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
2018
2053
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
2019
2054
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
2020
|
-
</svg>`;function le(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function
|
|
2055
|
+
</svg>`;function le(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function Y(r,e){return`
|
|
2021
2056
|
<div class="__crossx-row">
|
|
2022
2057
|
<span class="__crossx-row-label">${r}</span>
|
|
2023
2058
|
<div class="__crossx-row-value">${e}</div>
|
|
2024
|
-
</div>`}function
|
|
2025
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2059
|
+
</div>`}function Eo(r,e){const s=e,t=wt(r.dappName),n=r.to?`<span class="__crossx-addr-text">${ie(r.to)}</span>
|
|
2060
|
+
<button class="__crossx-copy-btn" data-copy="${C(r.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",i=Dr(r),o=r.data??"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
2026
2061
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2027
2062
|
<div class="__crossx-header">
|
|
2028
2063
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2033,10 +2068,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2033
2068
|
<div class="__crossx-body-cols">
|
|
2034
2069
|
<div class="__crossx-col-left">
|
|
2035
2070
|
<p class="__crossx-sig-subtitle">
|
|
2036
|
-
<span class="__crossx-sig-origin">${
|
|
2071
|
+
<span class="__crossx-sig-origin">${C(t)} </span>is requesting a Signature
|
|
2037
2072
|
</p>
|
|
2038
2073
|
<div class="__crossx-addr-pill">
|
|
2039
|
-
${
|
|
2074
|
+
${Qt}
|
|
2040
2075
|
<span class="__crossx-addr-pill-text">${ie(r.from)}</span>
|
|
2041
2076
|
</div>
|
|
2042
2077
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
@@ -2044,11 +2079,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2044
2079
|
<hr class="__crossx-divider __crossx-divider--cols">
|
|
2045
2080
|
<div class="__crossx-col-right-sign">
|
|
2046
2081
|
<div class="__crossx-rows">
|
|
2047
|
-
${
|
|
2048
|
-
${
|
|
2082
|
+
${Y("To",n)}
|
|
2083
|
+
${Y("Network",`<span>${Lr(r.chainId)}</span>`)}
|
|
2049
2084
|
${i}
|
|
2050
2085
|
</div>
|
|
2051
|
-
<pre class="__crossx-raw-tx">${
|
|
2086
|
+
<pre class="__crossx-raw-tx">${C(o)}</pre>
|
|
2052
2087
|
</div>
|
|
2053
2088
|
</div>
|
|
2054
2089
|
<div class="__crossx-btn-row">
|
|
@@ -2057,8 +2092,8 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2057
2092
|
</div>
|
|
2058
2093
|
</div>
|
|
2059
2094
|
</div>
|
|
2060
|
-
`,a}function
|
|
2061
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2095
|
+
`,a}function Ao(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,i=wt(r.dappName),o=r.to?`<span class="__crossx-addr-text">${ie(r.to)}</span>
|
|
2096
|
+
<button class="__crossx-copy-btn" data-copy="${C(r.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",a=Dr(r),l=fo(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
|
|
2062
2097
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2063
2098
|
<div class="__crossx-header">
|
|
2064
2099
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -2067,12 +2102,12 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2067
2102
|
<hr class="__crossx-divider">
|
|
2068
2103
|
<div class="__crossx-body">
|
|
2069
2104
|
<p class="__crossx-tx-subtitle">
|
|
2070
|
-
<span class="__crossx-sig-origin">${
|
|
2105
|
+
<span class="__crossx-sig-origin">${C(i)}</span> wants your permission to approve the following transaction.
|
|
2071
2106
|
</p>
|
|
2072
2107
|
<div class="__crossx-body-cols">
|
|
2073
2108
|
<div class="__crossx-rows">
|
|
2074
|
-
${
|
|
2075
|
-
${
|
|
2109
|
+
${Y("To",o)}
|
|
2110
|
+
${Y("Network",`<span>${Lr(r.chainId)}</span>`)}
|
|
2076
2111
|
${a}
|
|
2077
2112
|
</div>
|
|
2078
2113
|
<div class="__crossx-pill">
|
|
@@ -2083,12 +2118,12 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2083
2118
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
2084
2119
|
</div>
|
|
2085
2120
|
</div>
|
|
2086
|
-
`,
|
|
2087
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2088
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2089
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2121
|
+
`,d}function wt(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function C(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Io(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function To(r){if(typeof r=="string")return C(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return C(JSON.stringify(r))}catch{return String(r)}}function Ro(r,e){const s=Y("From",`<span class="__crossx-addr-text">${ie(r.from)}</span>
|
|
2122
|
+
<button class="__crossx-copy-btn" data-copy="${C(r.from)}" title="Copy address">${Te}</button>`),t=r.to?Y("To",`<span class="__crossx-addr-text">${ie(r.to)}</span>
|
|
2123
|
+
<button class="__crossx-copy-btn" data-copy="${C(r.to)}" title="Copy address">${Te}</button>`):"",n=r.amount?Y("Transfer",`<span>${C(r.amount)}</span>`):"",i=r.fees?Y("Tx Fee",`<span>${C(r.fees)}</span>`):"",o=r.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${ie(r.txHash)}</span>
|
|
2124
|
+
<button class="__crossx-copy-btn" data-copy="${C(r.txHash)}" title="Copy hash">${Te}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
2090
2125
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
2091
|
-
<span class="__crossx-total-amount">${
|
|
2126
|
+
<span class="__crossx-total-amount">${C(r.total)}</span>
|
|
2092
2127
|
</div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
2093
2128
|
<div class="__crossx-card __crossx-card--migration" style="${le(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2094
2129
|
<div class="__crossx-header">
|
|
@@ -2108,7 +2143,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2108
2143
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
2109
2144
|
</div>
|
|
2110
2145
|
</div>
|
|
2111
|
-
`,c}function
|
|
2146
|
+
`,c}function ko(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
2112
2147
|
<div class="__crossx-card __crossx-card--migration" style="${le(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2113
2148
|
<div class="__crossx-header">
|
|
2114
2149
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -2121,23 +2156,23 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2121
2156
|
</div>
|
|
2122
2157
|
</div>
|
|
2123
2158
|
</div>
|
|
2124
|
-
`,s}function
|
|
2125
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2126
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2127
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2159
|
+
`,s}function Oo(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=r.querySelector("#__crossx-ttl"),o=r.querySelector(".__crossx-header");if(i){const x=n?vo:t?"":So,S=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";x?(i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.innerHTML=`${x}<span>${S}</span>`):i.textContent=S}if(o&&!r.querySelector("#__crossx-close-btn")){const x=document.createElement("button");x.className="__crossx-close",x.id="__crossx-close-btn",x.setAttribute("aria-label","Close"),x.innerHTML=ce,o.appendChild(x)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?Y("From",`<span class="__crossx-addr-text">${ie(e.from)}</span>
|
|
2160
|
+
<button class="__crossx-copy-btn" data-copy="${C(e.from)}" title="Copy address">${Te}</button>`):"",l=e.to?Y("To",`<span class="__crossx-addr-text">${ie(e.to)}</span>
|
|
2161
|
+
<button class="__crossx-copy-btn" data-copy="${C(e.to)}" title="Copy address">${Te}</button>`):"",d=e.amount?Y("Transfer",`<span>${C(e.amount)}</span>`):"",f=e.fees?Y("Tx Fee",`<span>${C(e.fees)}</span>`):"",_=e.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${ie(e.txHash)}</span>
|
|
2162
|
+
<button class="__crossx-copy-btn" data-copy="${C(e.txHash)}" title="Copy hash">${Te}</button>`):"",p=e.total?`<div class="__crossx-total-pill">
|
|
2128
2163
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
2129
|
-
<span class="__crossx-total-amount">${
|
|
2164
|
+
<span class="__crossx-total-amount">${C(e.total)}</span>
|
|
2130
2165
|
</div>`:"";a.innerHTML=`
|
|
2131
2166
|
<div class="__crossx-rows">
|
|
2132
2167
|
${c}
|
|
2133
2168
|
${l}
|
|
2134
|
-
${
|
|
2169
|
+
${d}
|
|
2135
2170
|
${f}
|
|
2136
2171
|
${_}
|
|
2137
2172
|
</div>
|
|
2138
|
-
${
|
|
2173
|
+
${p}
|
|
2139
2174
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
2140
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",
|
|
2175
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(x=>{x.addEventListener("click",S=>{var I;S.stopPropagation();const E=x.dataset.copy;E&&((I=navigator.clipboard)==null||I.writeText(E).catch(()=>{}))})})}function Po(r,e){const s=e,t=wt(r.dappName),n=C(r.message),i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2141
2176
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2142
2177
|
<div class="__crossx-header">
|
|
2143
2178
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -2148,10 +2183,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2148
2183
|
<div class="__crossx-body-cols">
|
|
2149
2184
|
<div class="__crossx-col-left">
|
|
2150
2185
|
<p class="__crossx-sig-subtitle">
|
|
2151
|
-
<span class="__crossx-sig-origin">${
|
|
2186
|
+
<span class="__crossx-sig-origin">${C(t)} </span>is requesting a Signature
|
|
2152
2187
|
</p>
|
|
2153
2188
|
<div class="__crossx-addr-pill">
|
|
2154
|
-
${
|
|
2189
|
+
${Qt}
|
|
2155
2190
|
<span class="__crossx-addr-pill-text">${ie(r.from)}</span>
|
|
2156
2191
|
</div>
|
|
2157
2192
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
@@ -2165,15 +2200,15 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2165
2200
|
</div>
|
|
2166
2201
|
</div>
|
|
2167
2202
|
</div>
|
|
2168
|
-
`,i}function
|
|
2203
|
+
`,i}function Co(r,e){const s=e,t=wt(r.dappName);let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const i=n.primaryType??"—",o=n.message??{};let a=`
|
|
2169
2204
|
<div class="__crossx-td-row">
|
|
2170
2205
|
<span class="__crossx-td-label">Primary Type</span>
|
|
2171
|
-
<span class="__crossx-td-value">${
|
|
2172
|
-
</div>`;for(const[l,
|
|
2173
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2206
|
+
<span class="__crossx-td-value">${C(i)}</span>
|
|
2207
|
+
</div>`;for(const[l,d]of Object.entries(o)){const f=To(d),p=Io(d)?`<span class="__crossx-addr-text">${ie(d)}</span>
|
|
2208
|
+
<button class="__crossx-copy-btn" data-copy="${C(String(d))}" title="Copy">${Te}</button>`:`<span>${f}</span>`;a+=`
|
|
2174
2209
|
<div class="__crossx-td-row">
|
|
2175
|
-
<span class="__crossx-td-label">${
|
|
2176
|
-
<div class="__crossx-td-value">${
|
|
2210
|
+
<span class="__crossx-td-label">${C(l)}</span>
|
|
2211
|
+
<div class="__crossx-td-value">${p}</div>
|
|
2177
2212
|
</div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
2178
2213
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2179
2214
|
<div class="__crossx-header">
|
|
@@ -2185,10 +2220,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2185
2220
|
<div class="__crossx-body-cols">
|
|
2186
2221
|
<div class="__crossx-col-left">
|
|
2187
2222
|
<p class="__crossx-sig-subtitle">
|
|
2188
|
-
<span class="__crossx-sig-origin">${
|
|
2223
|
+
<span class="__crossx-sig-origin">${C(t)} </span>is requesting a Signature
|
|
2189
2224
|
</p>
|
|
2190
2225
|
<div class="__crossx-addr-pill">
|
|
2191
|
-
${
|
|
2226
|
+
${Qt}
|
|
2192
2227
|
<span class="__crossx-addr-pill-text">${ie(r.from)}</span>
|
|
2193
2228
|
</div>
|
|
2194
2229
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
@@ -2202,10 +2237,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2202
2237
|
</div>
|
|
2203
2238
|
</div>
|
|
2204
2239
|
</div>
|
|
2205
|
-
`,c}const
|
|
2240
|
+
`,c}const No=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2206
2241
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2207
2242
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2208
|
-
</svg>`;function
|
|
2243
|
+
</svg>`;function Lo(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(o=>{const a=t&&o.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${o.index}" data-wallet-address="${C(o.address)}">
|
|
2209
2244
|
<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${o.index+1}</span><span class="__crossx-wallet-addr">${ie(o.address)}</span></span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
2210
2245
|
</button>`}).join(""),i=document.createElement("div");return i.id=te,i.innerHTML=`
|
|
2211
2246
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${le(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
@@ -2231,31 +2266,31 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2231
2266
|
${n}
|
|
2232
2267
|
</div>
|
|
2233
2268
|
<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
|
|
2234
|
-
<span class="__crossx-wallet-add-icon">${
|
|
2269
|
+
<span class="__crossx-wallet-add-icon">${No}</span>
|
|
2235
2270
|
<span class="__crossx-wallet-add-label">add a wallet</span>
|
|
2236
2271
|
</button>
|
|
2237
2272
|
</div>
|
|
2238
2273
|
</div>
|
|
2239
2274
|
</div>
|
|
2240
2275
|
</div>
|
|
2241
|
-
`,i}const
|
|
2276
|
+
`,i}const Do=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2242
2277
|
<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"/>
|
|
2243
2278
|
<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"/>
|
|
2244
|
-
</svg>`,
|
|
2279
|
+
</svg>`,Mo=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2245
2280
|
<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"/>
|
|
2246
2281
|
<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"/>
|
|
2247
2282
|
<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"/>
|
|
2248
2283
|
<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"/>
|
|
2249
|
-
</svg>`;function
|
|
2284
|
+
</svg>`;function $o(r){const e=rs(r),s=bo[r]??"";return`<span role="button" tabindex="0" class="__crossx-connect-other-wallet--inline" data-wallet-id="${C(String(r))}"><span class="__crossx-connect-other-wallet-icon" aria-hidden="true">${s}</span><span class="__crossx-connect-other-wallet-name">${C(e)}</span></span>`}function Wo(r){if(r.length===0)return"";const e=n=>$o(r[n]),s="Supported wallets include ";if(r.length===1)return`${s}${e(0)}.`;if(r.length===2)return`${s}${e(0)} and ${e(1)}.`;if(r.length===3)return`${s}${e(0)}, ${e(1)} and ${e(2)}.`;const t=r.length-3;return`${s}${e(0)}, ${e(1)}, ${e(2)}, and ${t} more.`}function Uo(r,e=[]){const s=r,t=e.length>0?`
|
|
2250
2285
|
<div class="__crossx-login-or-divider">
|
|
2251
2286
|
<hr><span>or</span><hr>
|
|
2252
2287
|
</div>
|
|
2253
|
-
<
|
|
2288
|
+
<div class="__crossx-connect-other-block">
|
|
2254
2289
|
<div class="__crossx-connect-other-text">
|
|
2255
2290
|
<span class="__crossx-connect-other-title">Connect with Other Wallets</span>
|
|
2256
|
-
<
|
|
2291
|
+
<p class="__crossx-connect-other-desc __crossx-connect-other-summary">${Wo(e)}</p>
|
|
2257
2292
|
</div>
|
|
2258
|
-
</
|
|
2293
|
+
</div>`:"",n=document.createElement("div");return n.id=te,n.innerHTML=`
|
|
2259
2294
|
<div class="__crossx-card __crossx-card--migration" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2260
2295
|
<div class="__crossx-header">
|
|
2261
2296
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -2268,11 +2303,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2268
2303
|
<div class="__crossx-body">
|
|
2269
2304
|
<div class="__crossx-login-btn-row">
|
|
2270
2305
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
2271
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
2306
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${Do}</span>
|
|
2272
2307
|
<span class="__crossx-login-btn-label">Sign in with Apple</span>
|
|
2273
2308
|
</button>
|
|
2274
2309
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
2275
|
-
<span class="__crossx-login-icon">${
|
|
2310
|
+
<span class="__crossx-login-icon">${Mo}</span>
|
|
2276
2311
|
<span class="__crossx-login-btn-label">Sign in with Google</span>
|
|
2277
2312
|
</button>
|
|
2278
2313
|
</div>${t}
|
|
@@ -2281,29 +2316,29 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2281
2316
|
</p>
|
|
2282
2317
|
</div>
|
|
2283
2318
|
</div>
|
|
2284
|
-
`,n}function
|
|
2285
|
-
<p class="__crossx-session-account-label">${
|
|
2286
|
-
<p class="__crossx-session-account-email">${
|
|
2319
|
+
`,n}function Ho(r,e){const s=r,t=document.createElement("div");t.id=te;const n=C(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
|
|
2320
|
+
<p class="__crossx-session-account-label">${C(e.accountLabel)}</p>
|
|
2321
|
+
<p class="__crossx-session-account-email">${C(e.email)}</p>
|
|
2287
2322
|
</div>`:"";return t.innerHTML=`
|
|
2288
2323
|
<div class="__crossx-card __crossx-card--migration" style="${le(s)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
|
|
2289
2324
|
<div class="__crossx-header">
|
|
2290
|
-
<p class="__crossx-title" id="__crossx-session-header-title">${
|
|
2325
|
+
<p class="__crossx-title" id="__crossx-session-header-title">${C(e.title)}</p>
|
|
2291
2326
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
2292
2327
|
</div>
|
|
2293
2328
|
<hr class="__crossx-divider">
|
|
2294
2329
|
<div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
|
|
2295
2330
|
<div class="__crossx-session-hero">
|
|
2296
|
-
<p class="__crossx-session-hero-title">${
|
|
2331
|
+
<p class="__crossx-session-hero-title">${C(e.title)}</p>
|
|
2297
2332
|
<p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
|
|
2298
2333
|
</div>
|
|
2299
2334
|
${i}
|
|
2300
2335
|
<div class="__crossx-btn-row">
|
|
2301
|
-
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${
|
|
2302
|
-
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${
|
|
2336
|
+
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${C(e.signOutLabel)}</button>
|
|
2337
|
+
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${C(e.signInAgainLabel)}</button>
|
|
2303
2338
|
</div>
|
|
2304
2339
|
</div>
|
|
2305
2340
|
</div>
|
|
2306
|
-
`,t}function
|
|
2341
|
+
`,t}function Bo(r,e=!0){const s=r,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=`
|
|
2307
2342
|
<div class="__crossx-card __crossx-card--migration" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2308
2343
|
<div class="__crossx-header">
|
|
2309
2344
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2317,13 +2352,13 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2317
2352
|
<p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
|
|
2318
2353
|
</div>
|
|
2319
2354
|
<button class="__crossx-recover-btn" id="__crossx-recover-btn">
|
|
2320
|
-
<span class="__crossx-recover-icon">${
|
|
2355
|
+
<span class="__crossx-recover-icon">${xo}</span>
|
|
2321
2356
|
<span class="__crossx-recover-label">Import from Social Backup</span>
|
|
2322
2357
|
</button>
|
|
2323
2358
|
${n}
|
|
2324
2359
|
</div>
|
|
2325
2360
|
</div>
|
|
2326
|
-
`,i}function
|
|
2361
|
+
`,i}function Fo(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",f=document.createElement("div");return f.id=te,f.innerHTML=`
|
|
2327
2362
|
<div class="__crossx-card __crossx-card--migration" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2328
2363
|
<div class="__crossx-header">
|
|
2329
2364
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2340,10 +2375,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2340
2375
|
<input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
|
|
2341
2376
|
</div>
|
|
2342
2377
|
<p class="__crossx-pin-hint">Enter your 4-digit PIN to recover your wallet.</p>
|
|
2343
|
-
${
|
|
2378
|
+
${d}
|
|
2344
2379
|
</div>
|
|
2345
2380
|
</div>
|
|
2346
|
-
`,f}function
|
|
2381
|
+
`,f}function Ko(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function Go(r,e,s){const t=r,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?Ko(i):null,a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
2347
2382
|
<div class="__crossx-card __crossx-card--migration" style="${le(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2348
2383
|
<div class="__crossx-header">
|
|
2349
2384
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
@@ -2363,15 +2398,15 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2363
2398
|
</div>
|
|
2364
2399
|
</div>
|
|
2365
2400
|
</div>
|
|
2366
|
-
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const f=setInterval(()=>{Date.now()>=i&&(clearInterval(f),l())},1e3);return()=>clearInterval(f)}}}function
|
|
2401
|
+
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const f=setInterval(()=>{Date.now()>=i&&(clearInterval(f),l())},1e3);return()=>clearInterval(f)}}}function qo(r){const s=[r.check1,r.check2].map((t,n)=>`
|
|
2367
2402
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2368
|
-
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${
|
|
2369
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
2403
|
+
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Yo}</div>
|
|
2404
|
+
<span class="__crossx-pw-notice-item-text">${C(t)}</span>
|
|
2370
2405
|
</div>
|
|
2371
2406
|
`).join("");return`
|
|
2372
2407
|
<div class="__crossx-header">
|
|
2373
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2374
|
-
<p class="__crossx-pw-subtitle">${
|
|
2408
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${C(r.title)}</p>
|
|
2409
|
+
<p class="__crossx-pw-subtitle">${C(r.headerSubtitle)}</p>
|
|
2375
2410
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
2376
2411
|
</div>
|
|
2377
2412
|
<hr class="__crossx-divider">
|
|
@@ -2379,50 +2414,50 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2379
2414
|
<div class="__crossx-pw-fields __crossx-pw-fields--notice">
|
|
2380
2415
|
<div class="__crossx-pw-notice-header">
|
|
2381
2416
|
<div class="__crossx-pw-notice-title-row">
|
|
2382
|
-
<span class="__crossx-pw-notice-icon">${
|
|
2383
|
-
<p class="__crossx-pw-notice-title">${
|
|
2417
|
+
<span class="__crossx-pw-notice-icon">${jo}</span>
|
|
2418
|
+
<p class="__crossx-pw-notice-title">${C(r.noticeTitle)}</p>
|
|
2384
2419
|
</div>
|
|
2385
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2420
|
+
<p class="__crossx-pw-notice-desc">${C(r.noticeDesc)}</p>
|
|
2386
2421
|
</div>
|
|
2387
2422
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2388
2423
|
${s}
|
|
2389
2424
|
</div>
|
|
2390
2425
|
</div>
|
|
2391
2426
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2392
|
-
data-next-label="${
|
|
2393
|
-
data-submit-label="${
|
|
2394
|
-
${
|
|
2427
|
+
data-next-label="${C(r.nextButton)}"
|
|
2428
|
+
data-submit-label="${C(r.submitButton)}">
|
|
2429
|
+
${C(r.nextButton)}
|
|
2395
2430
|
</button>
|
|
2396
2431
|
</div>
|
|
2397
2432
|
<div class="__crossx-home-indicator"></div>
|
|
2398
|
-
`}function
|
|
2399
|
-
${
|
|
2433
|
+
`}function es(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${C(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${C(r.subtitle)}</p>`:"",i=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${C(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2434
|
+
${$r}
|
|
2400
2435
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2401
|
-
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${
|
|
2436
|
+
</p>`:"",a=r.warningMessage&&r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${C(r.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=r.attemptCount!=null&&r.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${r.attemptCount}/${r.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",d=Array.from({length:6},(S,E)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${E+1}"${e?" disabled":""}>`).join(""),f=e?" --locked":"",_=Array.from({length:6},(S,E)=>`<div class="__crossx-pin6-dot${f}" data-dot-index="${E}" aria-label="PIN digit ${E+1}"></div>`).join(""),p=e?" --disabled":"",x=`
|
|
2402
2437
|
<div class="__crossx-pin6-numpad" id="__crossx-pin6-numpad">
|
|
2403
2438
|
<div class="__crossx-pin6-numpad-row">
|
|
2404
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2405
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2406
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2439
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="1">1</button>
|
|
2440
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="2">2</button>
|
|
2441
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="3">3</button>
|
|
2407
2442
|
</div>
|
|
2408
2443
|
<div class="__crossx-pin6-numpad-row">
|
|
2409
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2410
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2411
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2444
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="4">4</button>
|
|
2445
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="5">5</button>
|
|
2446
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="6">6</button>
|
|
2412
2447
|
</div>
|
|
2413
2448
|
<div class="__crossx-pin6-numpad-row">
|
|
2414
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2415
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2416
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2449
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="7">7</button>
|
|
2450
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="8">8</button>
|
|
2451
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="9">9</button>
|
|
2417
2452
|
</div>
|
|
2418
2453
|
<div class="__crossx-pin6-numpad-row">
|
|
2419
2454
|
<button type="button" class="__crossx-pin6-numpad-key --empty" aria-hidden="true"></button>
|
|
2420
|
-
<button type="button" class="__crossx-pin6-numpad-key${
|
|
2421
|
-
<button type="button" class="__crossx-pin6-numpad-key --delete${
|
|
2455
|
+
<button type="button" class="__crossx-pin6-numpad-key${p}" data-key="0">0</button>
|
|
2456
|
+
<button type="button" class="__crossx-pin6-numpad-key --delete${p}" data-key="backspace" aria-label="Delete">${zo}</button>
|
|
2422
2457
|
</div>
|
|
2423
2458
|
</div>`;return`
|
|
2424
2459
|
<div class="__crossx-header">
|
|
2425
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2460
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${C(r.title)}</p>
|
|
2426
2461
|
${t}
|
|
2427
2462
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
2428
2463
|
</div>
|
|
@@ -2430,7 +2465,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2430
2465
|
<div class="__crossx-pin6-body"${s}>
|
|
2431
2466
|
${n}
|
|
2432
2467
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
2433
|
-
${
|
|
2468
|
+
${d}
|
|
2434
2469
|
<div class="__crossx-pin6-dots" id="__crossx-pin6-dots">
|
|
2435
2470
|
${_}
|
|
2436
2471
|
</div>
|
|
@@ -2441,18 +2476,18 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2441
2476
|
${o}
|
|
2442
2477
|
</div>
|
|
2443
2478
|
${x}
|
|
2444
|
-
`}function
|
|
2479
|
+
`}function Mr(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
2445
2480
|
<div class="__crossx-card __crossx-card--pin6" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2446
2481
|
${e}
|
|
2447
2482
|
</div>
|
|
2448
|
-
`,s}function
|
|
2483
|
+
`,s}function Jo(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((i,o)=>o===0||i===(s[o-1]+1)%10),n=s.every((i,o)=>o===0||i===(s[o-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function Vo(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function ts(r,e,s,t,n,i,o){var O,D;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),d=()=>r.querySelector("#__crossx-pin6-boxes"),f=()=>r.querySelector("#__crossx-pin6-error"),_=()=>r.querySelector("#__crossx-pin6-lock-msg"),p=()=>r.querySelector("#__crossx-pin6-lock-countdown"),x=()=>r.querySelector(".__crossx-pin6-body"),S=()=>l().map(y=>y.value).join(""),E=()=>Array.from(r.querySelectorAll(".__crossx-pin6-dot")),I=()=>{var v;const y=l(),b=E();if(b.length&&(b.forEach((A,R)=>{const H=!!(y[R]&&y[R].value);A.classList.toggle("--filled",H),A.classList.toggle("--active",!1)}),!a&&!c)){const A=y.findIndex(H=>!H.value);(v=b[A===-1?5:A])==null||v.classList.add("--active")}},k=()=>{r.querySelectorAll(".__crossx-pin6-numpad-key[data-key]").forEach(b=>b.classList.toggle("--disabled",a)),E().forEach(b=>b.classList.toggle("--locked",a)),I()},B=y=>{a=y,l().forEach(b=>{b.disabled=y,b.classList.toggle("--locked",y)})},$=()=>r.querySelector("#__crossx-pin6-attempt"),J=()=>{const y=f();y&&(y.textContent="")},G=()=>o??"Your account will be locked after further failures.",se=()=>r.querySelector("#__crossx-pin6-warning"),F=y=>{var v;let b=se();if(!b){b=document.createElement("p"),b.className="__crossx-pin6-warning",b.id="__crossx-pin6-warning";const A=f();A?A.insertAdjacentElement("afterend",b):(v=x())==null||v.appendChild(b)}b.textContent=y},X=()=>{const y=se();y&&(y.textContent="")},re=(y,b)=>{var A;let v=$();if(!v){v=document.createElement("p"),v.className="__crossx-pin6-attempt",v.id="__crossx-pin6-attempt";const R=se()??f();R?R.insertAdjacentElement("afterend",v):(A=x())==null||A.appendChild(v)}v.textContent=`${y}/${b}`},U=()=>{const y=$();y&&(y.textContent="")},N=y=>{const b=f();b&&(b.textContent=y);const v=d();v==null||v.classList.add("--shake"),setTimeout(()=>v==null?void 0:v.classList.remove("--shake"),500),l().forEach(A=>{A.value=""}),setTimeout(()=>{var A;(A=l()[0])==null||A.focus(),I()},50)},M=y=>{var H;B(!0),l().forEach(W=>{W.value=""}),k();const b=f();if(b&&(b.textContent="Too many failed attempts. Please wait."),!_()){const W=document.createElement("p");W.className="__crossx-pin6-lock-msg",W.id="__crossx-pin6-lock-msg",W.innerHTML=`${$r}<span id="__crossx-pin6-lock-countdown"></span>`;const L=f();L?L.insertAdjacentElement("afterend",W):(H=x())==null||H.appendChild(W)}const v=()=>{var K;const W=y-Date.now(),L=p();W<=0?(clearInterval(A),B(!1),(K=_())==null||K.remove(),b&&(b.textContent=""),k(),setTimeout(()=>{var j;return(j=l()[0])==null?void 0:j.focus()},50)):L&&(L.textContent=` ${Vo(W)}`)},A=setInterval(v,1e3);v();const R=new MutationObserver(()=>{document.contains(r)||(clearInterval(A),R.disconnect())});R.observe(document.body,{childList:!0,subtree:!1})},m=async()=>{if(a||c)return;const y=S();if(y.length===6){c=!0,l().forEach(b=>{b.disabled=!0});try{if(n){const b=await n(y);b.ok?e(y):b.lockExpiresAt?(U(),M(b.lockExpiresAt)):(N(b.error??"Incorrect PIN. Please try again."),b.attemptCount!=null&&b.maxAttempts!=null?(F(G()),re(b.attemptCount,b.maxAttempts)):(X(),U()))}else e(y)}catch(b){t&&t(b)}finally{c=!1,a||l().forEach(b=>{b.disabled=!1}),I()}}};i&&i>Date.now()?M(i):setTimeout(()=>{var y;return(y=l()[0])==null?void 0:y.focus()},100);const w=()=>{if(a||c)return;const y=l(),b=y.find(v=>!v.value)??y[y.length-1];b==null||b.focus()};(O=d())==null||O.addEventListener("click",y=>{y.target.classList.contains("__crossx-pin6-box")||w()}),(D=x())==null||D.addEventListener("click",y=>{const b=y.target;b.classList.contains("__crossx-pin6-box")||b.closest("button")||w()}),l().forEach((y,b)=>{y.addEventListener("input",()=>{var A;const v=y.value.replace(/\D/g,"").slice(-1);y.value=v,J(),v&&b<5&&((A=l()[b+1])==null||A.focus()),I(),S().length===6&&setTimeout(m,80)}),y.addEventListener("keydown",v=>{var A,R;if(v.key==="Backspace"){if(v.preventDefault(),y.value)y.value="";else if(b>0){const H=l()[b-1];H.value="",H.focus()}I()}else v.key==="ArrowLeft"&&b>0?(v.preventDefault(),(A=l()[b-1])==null||A.focus()):v.key==="ArrowRight"&&b<5?(v.preventDefault(),(R=l()[b+1])==null||R.focus()):v.key==="Escape"&&s()}),y.addEventListener("paste",v=>{var H,W;v.preventDefault();const A=(((H=v.clipboardData)==null?void 0:H.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!A)return;const R=l();A.split("").forEach((L,K)=>{R[K]&&(R[K].value=L)}),(W=R[Math.min(A.length-1,5)])==null||W.focus(),J(),I(),S().length===6&&setTimeout(m,80)}),y.addEventListener("focus",()=>y.select())});const T=r.querySelector("#__crossx-pin6-numpad");if(T){let y=null;const b=()=>{y&&(y.classList.remove("--pressed"),y=null)};T.addEventListener("pointerdown",A=>{const R=A.target.closest(".__crossx-pin6-numpad-key");!R||a||c||(b(),y=R,R.classList.add("--pressed"),R.setPointerCapture(A.pointerId))});const v=A=>{const R=A.dataset.key;if(!R)return;if(R==="backspace"){const K=[...l()].reverse().find(j=>j.value);K&&(K.value="",J()),I();return}if(!/^\d$/.test(R))return;const W=l().find(L=>!L.value);W&&(W.value=R,J(),I(),S().length===6&&setTimeout(m,80))};T.addEventListener("pointerup",A=>{if(!y)return;const R=y;b();const H=R.getBoundingClientRect();A.clientX>=H.left&&A.clientX<=H.right&&A.clientY>=H.top&&A.clientY<=H.bottom&&!a&&!c&&v(R)}),T.addEventListener("pointercancel",b),T.addEventListener("pointerleave",b,!0),I(),i&&i>Date.now()&&k()}}const zo=`<svg width="22" height="17" viewBox="0 0 22 17" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2449
2484
|
<path d="M7.36 0.5H19.5C20.6046 0.5 21.5 1.39543 21.5 2.5V14.5C21.5 15.6046 20.6046 16.5 19.5 16.5H7.36C6.76 16.5 6.19 16.24 5.8 15.79L0.94 10.02C0.35 9.32 0.35 8.3 0.94 7.6L5.8 1.71C6.19 1.26 6.76 0.5 7.36 0.5Z" stroke="currentColor" stroke-width="1.2" fill="none"/>
|
|
2450
2485
|
<line x1="10" y1="5.5" x2="16" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
2451
2486
|
<line x1="16" y1="5.5" x2="10" y2="11.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
|
|
2452
|
-
</svg
|
|
2487
|
+
</svg>`,$r=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2453
2488
|
<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"/>
|
|
2454
|
-
</svg>`,
|
|
2489
|
+
</svg>`,Yo=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2455
2490
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2456
|
-
</svg>`,
|
|
2491
|
+
</svg>`,jo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2457
2492
|
<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"/>
|
|
2458
|
-
</svg>`;function Ho(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,h)=>{t[h]&&(t[h].value=_)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",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 Bo{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=kr(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=kr(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var v;fe();const i=[...e],o=Ao(i,this.tokens,t),a=ze();_e(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},u=E=>{l(),n(E)},f=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(E=>{E.addEventListener("click",()=>{const T=E.dataset.walletAddress??"",k=parseInt(E.dataset.walletIndex??"0",10);u({address:T,index:k})})})})();const h=o.querySelector("#__crossx-add-wallet-btn");h&&h.addEventListener("click",async()=>{h.disabled=!0;try{const E=await s();i.push(E);const T=o.querySelector("#__crossx-wallet-list");if(T){const k=document.createElement("button");k.className="__crossx-wallet-item",k.dataset.walletIndex=String(E.index),k.dataset.walletAddress=E.address,k.innerHTML=`<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${E.index+1}</span><span class="__crossx-wallet-addr">${ie(E.address)}</span></span>`,k.addEventListener("click",()=>u(E)),T.appendChild(k),k.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{h.disabled=!1}}),(v=o.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",f),o.addEventListener("click",E=>{E.target===o&&f()});const x=E=>{E.key==="Escape"&&(document.removeEventListener("keydown",x),f())};document.addEventListener("keydown",x)})}showLoginSelector(e){return new Promise(s=>{var l,u,f,_;fe();const t=Ro(this.tokens,e==null?void 0:e.showConnectOtherWallets),n=ze();_e(t);const i=()=>{t.remove(),n()},o=h=>{i(),s(h)},a=()=>{i(),s(null)};(l=t.querySelector("#__crossx-apple-btn"))==null||l.addEventListener("click",()=>o("apple")),(u=t.querySelector("#__crossx-google-btn"))==null||u.addEventListener("click",()=>o("google")),(f=t.querySelector("#__crossx-connect-btn"))==null||f.addEventListener("click",()=>o("external")),(_=t.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",a),t.addEventListener("click",h=>{h.target===t&&a()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(h=>{h.addEventListener("click",x=>x.stopPropagation())});const c=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}showSessionAlert(e){return new Promise(s=>{var u,f,_;fe();const t=this.messages,n=ko(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=ze();_e(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;fe();const n=Oo(this.tokens,s);_e(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",_=>{_.target===n&&u()});const f=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(s=>{fe();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=Nr(this.tokens,Lo(n)),c=ze();_e(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=k=>{u(),s(k)},_=()=>{u(),s(null)},h=a.querySelector(".__crossx-card"),x={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},v=k=>{var B;h.innerHTML=Qt({title:o.title,headerSubtitle:o.headerSubtitle}),(B=h.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",_),es(h,$=>{$===k?f(k):E(i.mismatchError)},_)},E=k=>{var B;h.innerHTML=Qt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:k}),(B=h.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",_),es(h,$=>{const J=Do($,x);J?E(J):v($)},_)};(()=>{var re;const k=Array.from(h.querySelectorAll(".__crossx-pw-notice-item")),B=h.querySelector("#__crossx-pin-notice-next"),$=new Set;B.removeAttribute("disabled");const J=B.dataset.nextLabel??"Next",G=B.dataset.submitLabel??"I Understand",se=()=>{const U=$.size===k.length;B.classList.toggle("--disabled",!U),B.textContent=U?G:J},F=(U,C)=>{if($.has(C))return;const M=U.querySelector(`#__crossx-notice-check-${C}`);$.add(C),M.classList.add("--checked"),U.setAttribute("aria-checked","true"),se()},j=(U,C)=>{if(!$.has(C))return;const M=U.querySelector(`#__crossx-notice-check-${C}`);$.delete(C),M.classList.remove("--checked"),U.setAttribute("aria-checked","false"),se()};k.forEach(U=>{const C=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{$.has(C)?j(U,C):F(U,C)}),U.addEventListener("keydown",M=>{(M.key===" "||M.key==="Enter")&&(M.preventDefault(),$.has(C)?j(U,C):F(U,C))})}),B.addEventListener("click",()=>{if($.size===k.length){E(e==null?void 0:e.errorMessage);return}const U=k.find(M=>{const m=parseInt(M.dataset.checkIndex??"0",10);return!$.has(m)});if(!U)return;const C=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),F(U,C)},400)}),(re=h.querySelector("#__crossx-close-btn"))==null||re.addEventListener("click",_)})(),a.addEventListener("click",k=>{k.target===a&&_()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var T;fe();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=Nr(this.tokens,Qt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=ze();_e(l);let f=!1;const _=()=>{f||(f=!0,l.remove(),u())},h=k=>{_(),s(k)},x=()=>{_(),s(null)},v=k=>{_(),t(k)},E=l.querySelector(".__crossx-card");(T=E.querySelector("#__crossx-close-btn"))==null||T.addEventListener("click",x),es(E,h,x,v,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",k=>{k.target===l&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;fe();const t=Po(this.tokens,e);_e(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};Ho(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;fe();const{overlay:n,startCountdown:i}=No(this.tokens,e,s);_e(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;fe();const t=wo(e,this.tokens);_e(t);const n=()=>t.remove(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var _;u.stopPropagation();const f=l.dataset.copy;f&&((_=navigator.clipboard)==null||_.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{fe();const n=yo(e,this.tokens);_e(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,f;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{o||(bo(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,u,f;fe();let t;e.type==="sign-message"?t=So(e,this.tokens):e.type==="sign-typed-data"?t=vo(e,this.tokens):e.type==="sign"?t=_o(e,this.tokens):t=go(e,this.tokens);const n=ze();_e(t);const i=()=>{t.remove(),n()},o=()=>{i(),s(!0)},a=()=>{i(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-cancel-btn"))==null||u.addEventListener("click",a),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",h=>{var v;h.stopPropagation();const x=_.dataset.copy;x&&((v=navigator.clipboard)==null||v.writeText(x).catch(()=>{}))})}),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Dr{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Fo(r,e){r.debug;const s=We.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},i=t.authMode!=="cookie"&&ps.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new ps(r.projectId):new sn,a=new Zi,c=new so,l=new Me,u=new Dr,f=new vt;let _;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),_=new no(o,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),_=new $e(n,o,c,u,f));const h=new tt(n,c),x=new Bo(r.theme??"light",r.themeTokens),v=e!=null&&e.wrapConfirmation?e.wrapConfirmation(x):x,E=new nt(t,n,o,a,c,l,_,u,v,h,f);return typeof window<"u"&&(window.__crossxSDK=E),E}function Ko(r){const e=Go(r),s=qo(e),t=JSON.parse(s);Vo(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Go(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function qo(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=Jo(r);return decodeURIComponent(e)}function Jo(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Vo(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return Q.CROSSxError=g,Q.CROSSxEthereumProvider=ts,Q.CROSSxSDK=nt,Q.ChainId=Ur,Q.ErrorCode=p,Q.PinMemoryStore=vt,Q.TokenMemoryStore=Dr,Q.createCROSSxSDK=Fo,Q.parseOAuthDeeplink=Ko,Object.defineProperty(Q,Symbol.toStringTag,{value:"Module"}),Q}({});
|
|
2493
|
+
</svg>`;function Xo(r,e,s){var i;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(d=>d.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((_,p)=>{t[p]&&(t[p].value=_)});const d=Math.min(l.length,3);t[d].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Zo{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Cr(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Cr(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var S;fe();const i=[...e],o=Lo(i,this.tokens,t),a=Ye();_e(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},d=E=>{l(),n(E)},f=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(E=>{E.addEventListener("click",()=>{const I=E.dataset.walletAddress??"",k=parseInt(E.dataset.walletIndex??"0",10);d({address:I,index:k})})})})();const p=o.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const E=await s();i.push(E);const I=o.querySelector("#__crossx-wallet-list");if(I){const k=document.createElement("button");k.className="__crossx-wallet-item",k.dataset.walletIndex=String(E.index),k.dataset.walletAddress=E.address,k.innerHTML=`<span class="__crossx-wallet-info"><span class="__crossx-wallet-idx">Account ${E.index+1}</span><span class="__crossx-wallet-addr">${ie(E.address)}</span></span>`,k.addEventListener("click",()=>d(E)),I.appendChild(k),k.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(S=o.querySelector("#__crossx-close-btn"))==null||S.addEventListener("click",f),o.addEventListener("click",E=>{E.target===o&&f()});const x=E=>{E.key==="Escape"&&(document.removeEventListener("keydown",x),f())};document.addEventListener("keydown",x)})}showLoginSelector(e){var t;const s=((t=e==null?void 0:e.connectOtherWallets)==null?void 0:t.filter(n=>Object.values(We).includes(n)&&String(n).trim()!==""))??[];return new Promise(n=>{var _,p,x;fe();const i=Uo(this.tokens,s),o=Ye();_e(i);const a=()=>{i.remove(),o()},c=S=>{a(),n({type:"oauth",provider:S})},l=S=>{a(),n({type:"external",walletId:S})},d=()=>{a(),n(null)};(_=i.querySelector("#__crossx-apple-btn"))==null||_.addEventListener("click",()=>c("apple")),(p=i.querySelector("#__crossx-google-btn"))==null||p.addEventListener("click",()=>c("google")),i.querySelectorAll(".__crossx-connect-other-wallet--inline").forEach(S=>{const E=()=>{const I=S.dataset.walletId??"";l(I)};S.addEventListener("click",E),S.addEventListener("keydown",I=>{(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),E())})}),(x=i.querySelector("#__crossx-close-btn"))==null||x.addEventListener("click",d),i.addEventListener("click",S=>{S.target===i&&d()}),i.querySelectorAll(".__crossx-login-terms-link").forEach(S=>{S.addEventListener("click",E=>E.stopPropagation())});const f=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",f),d())};document.addEventListener("keydown",f)})}showSessionAlert(e){return new Promise(s=>{var d,f,_;fe();const t=this.messages,n=Ho(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=Ye();_e(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),s("signout")},l=()=>{a(),s("signin-again")};(d=n.querySelector("#__crossx-session-signout"))==null||d.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(_=n.querySelector("#__crossx-close-btn"))==null||_.addEventListener("click",c)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;fe();const n=Bo(this.tokens,s);_e(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),s){const d=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",d),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",d),n.addEventListener("click",_=>{_.target===n&&d()});const f=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",f),d())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(s=>{fe();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=Mr(this.tokens,qo(n)),c=Ye();_e(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())},f=k=>{d(),s(k)},_=()=>{d(),s(null)},p=a.querySelector(".__crossx-card"),x={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."},S=k=>{var B;p.innerHTML=es({title:o.title,headerSubtitle:o.headerSubtitle}),(B=p.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",_),ts(p,$=>{$===k?f(k):E(i.mismatchError)},_)},E=k=>{var B;p.innerHTML=es({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:k}),(B=p.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",_),ts(p,$=>{const J=Jo($,x);J?E(J):S($)},_)};(()=>{var re;const k=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),B=p.querySelector("#__crossx-pin-notice-next"),$=new Set;B.removeAttribute("disabled");const J=B.dataset.nextLabel??"Next",G=B.dataset.submitLabel??"I Understand",se=()=>{const U=$.size===k.length;B.classList.toggle("--disabled",!U),B.textContent=U?G:J},F=(U,N)=>{if($.has(N))return;const M=U.querySelector(`#__crossx-notice-check-${N}`);$.add(N),M.classList.add("--checked"),U.setAttribute("aria-checked","true"),se()},X=(U,N)=>{if(!$.has(N))return;const M=U.querySelector(`#__crossx-notice-check-${N}`);$.delete(N),M.classList.remove("--checked"),U.setAttribute("aria-checked","false"),se()};k.forEach(U=>{const N=parseInt(U.dataset.checkIndex??"0",10);U.addEventListener("click",()=>{$.has(N)?X(U,N):F(U,N)}),U.addEventListener("keydown",M=>{(M.key===" "||M.key==="Enter")&&(M.preventDefault(),$.has(N)?X(U,N):F(U,N))})}),B.addEventListener("click",()=>{if($.size===k.length){E(e==null?void 0:e.errorMessage);return}const U=k.find(M=>{const m=parseInt(M.dataset.checkIndex??"0",10);return!$.has(m)});if(!U)return;const N=parseInt(U.dataset.checkIndex??"0",10);U.scrollIntoView({behavior:"smooth",block:"nearest"}),U.classList.add("--highlight"),setTimeout(()=>{U.classList.remove("--highlight"),F(U,N)},400)}),(re=p.querySelector("#__crossx-close-btn"))==null||re.addEventListener("click",_)})(),a.addEventListener("click",k=>{k.target===a&&_()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var I;fe();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=Mr(this.tokens,es({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),d=Ye();_e(l);let f=!1;const _=()=>{f||(f=!0,l.remove(),d())},p=k=>{_(),s(k)},x=()=>{_(),s(null)},S=k=>{_(),t(k)},E=l.querySelector(".__crossx-card");(I=E.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",x),ts(E,p,x,S,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",k=>{k.target===l&&x()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;fe();const t=Fo(this.tokens,e);_e(t);const n=()=>t.remove(),i=c=>{n(),s(c)},o=()=>{n(),s(null)};Xo(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;fe();const{overlay:n,startCountdown:i}=Go(this.tokens,e,s);_e(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;fe();const t=Ro(e,this.tokens);_e(t);const n=()=>t.remove(),i=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var _;d.stopPropagation();const f=l.dataset.copy;f&&((_=navigator.clipboard)==null||_.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,s){return new Promise(t=>{fe();const n=ko(e,this.tokens);_e(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var d,f;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",_=>{_.target===n&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{o||(Oo(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var l,d,f;fe();let t;e.type==="sign-message"?t=Po(e,this.tokens):e.type==="sign-typed-data"?t=Co(e,this.tokens):e.type==="sign"?t=Eo(e,this.tokens):t=Ao(e,this.tokens);const n=Ye();_e(t);const i=()=>{t.remove(),n()},o=()=>{i(),s(!0)},a=()=>{i(),s(!1)};(l=t.querySelector("#__crossx-confirm-btn"))==null||l.addEventListener("click",o),(d=t.querySelector("#__crossx-cancel-btn"))==null||d.addEventListener("click",a),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),t.querySelectorAll(".__crossx-copy-btn").forEach(_=>{_.addEventListener("click",p=>{var S;p.stopPropagation();const x=_.dataset.copy;x&&((S=navigator.clipboard)==null||S.writeText(x).catch(()=>{}))})}),t.addEventListener("click",_=>{_.target===t&&a()});const c=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",c),a())};document.addEventListener("keydown",c)})}}class Wr{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Qo(r,e){r.debug;const s=Ue.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},i=t.authMode!=="cookie"&&gs.isAvailable();!i&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new gs(r.projectId):new cn,a=new ro,c=new ao,l=new Me,d=new Wr,f=new Et;let _;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),_=new lo(o,f)):(u.log("[CROSSx] Remote Wallet Provider 사용"),_=new $e(n,o,c,d,f));const p=new st(n,c),x=new Zo(r.theme??"light",r.themeTokens),S=e!=null&&e.wrapConfirmation?e.wrapConfirmation(x):x,E=new it(t,n,o,a,c,l,_,d,S,p,f);return typeof window<"u"&&(window.__crossxSDK=E),E}function ea(r){const e=ta(r),s=sa(e),t=JSON.parse(s);na(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 ta(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function sa(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=ra(r);return decodeURIComponent(e)}function ra(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function na(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return z.CONNECT_OTHER_WALLET_DISPLAY_ORDER=ss,z.CROSSxError=g,z.CROSSxEthereumProvider=ns,z.CROSSxSDK=it,z.ChainId=Gr,z.ConnectOtherWalletItem=We,z.ErrorCode=h,z.PinMemoryStore=Et,z.TokenMemoryStore=Wr,z.createCROSSxSDK=Qo,z.getConnectOtherWalletLabel=rs,z.parseOAuthDeeplink=ea,Object.defineProperty(z,Symbol.toStringTag,{value:"Module"}),z}({});
|