@nexus-cross/crossx-sdk-core 1.2.4-beta.1 → 1.2.5
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/crypto/JoseCryptoAdapter.d.ts +2 -0
- package/dist/adapters/crypto/JoseCryptoAdapter.d.ts.map +1 -1
- package/dist/adapters/oauth/BrowserOAuthAdapter.d.ts.map +1 -1
- package/dist/adapters/storage/IndexedDBStorageAdapter.d.ts +7 -0
- package/dist/adapters/storage/IndexedDBStorageAdapter.d.ts.map +1 -1
- package/dist/adapters/transport/FetchTransportAdapter.d.ts +1 -0
- package/dist/adapters/transport/FetchTransportAdapter.d.ts.map +1 -1
- package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
- package/dist/core/constants.d.ts +2 -2
- package/dist/core/constants.d.ts.map +1 -1
- package/dist/core/ports/CryptoPort.d.ts +5 -0
- package/dist/core/ports/CryptoPort.d.ts.map +1 -1
- package/dist/core/ports/TransportPort.d.ts +2 -0
- package/dist/core/ports/TransportPort.d.ts.map +1 -1
- package/dist/core/services/JsonRpcService.d.ts +1 -0
- package/dist/core/services/JsonRpcService.d.ts.map +1 -1
- package/dist/core/services/TokenMemoryStore.d.ts +1 -0
- package/dist/core/services/TokenMemoryStore.d.ts.map +1 -1
- package/dist/core/types/internal.d.ts +5 -0
- package/dist/core/types/internal.d.ts.map +1 -1
- package/dist/core/usecases/SignInUseCase.d.ts +10 -0
- package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
- package/dist/core/usecases/SignOutUseCase.d.ts +3 -0
- package/dist/core/usecases/SignOutUseCase.d.ts.map +1 -1
- package/dist/crossx.global +116 -116
- package/dist/index.cjs +31 -31
- package/dist/index.js +965 -824
- package/dist/sdk/CROSSxSDK.d.ts +11 -0
- package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
- package/dist/sdk/factory.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/crossx.global
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
var CROSSx=function(ne){"use strict";var go=Object.defineProperty;var mo=(ne,p,f)=>p in ne?go(ne,p,{enumerable:!0,configurable:!0,writable:!0,value:f}):ne[p]=f;var I=(ne,p,f)=>mo(ne,typeof p!="symbol"?p+"":p,f);var p=(r=>(r.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",r.AUTH_FAILED="AUTH_FAILED",r.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",r.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",r.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",r.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",r.WALLET_NOT_FOUND="WALLET_NOT_FOUND",r.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_CANCELLED="PIN_CANCELLED",r.PIN_LOCKED="PIN_LOCKED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class f extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,f.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const He={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},$s=Object.fromEntries(Object.entries(He).map(([r,e])=>[r,e.caipId])),Bs=new Map(Object.values(He).map(r=>[r.caipId,r]));new Map(Object.values(He).map(r=>[r.chainId,r]));const Us={symbol:"",decimals:18};function tt(r){var e;return((e=Bs.get(r))==null?void 0:e.nativeCurrency)??Us}class St{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new f(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new f(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let Se=null;function wo(r){}function It(r){Se=r}const u={log(...r){if(Se){Se.log(...r);return}},warn(...r){if(Se){Se.warn(...r);return}},error(...r){if(Se){Se.error(...r);return}}},Hs={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간"},Et={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from"},Fs={ko:Hs,en:Et};function Tt(r="en",e){return Fs[r]??Et}const Fe="crossx_access_token",Ce="crossx_refresh_token",Le="crossx_user_info";class Ws{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new f(p.AUTH_FAILED,`${s} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new f(p.AUTH_FAILED,`${s} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:h}=this.config,m=`${d}${l}`;u.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const g=await this.oauth.openAuth({authUrl:m,expectedOrigin:new URL(d).origin});u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",g.length,")");const{accessToken:w,refreshToken:E}=await this.exchangeFirebaseToken(g,h);let y,S;try{const U=this.crypto.decodeJWT(g);S=(n=U.firebase)==null?void 0:n.sign_in_provider;const b=((o=U.firebase)==null?void 0:o.identities)??{};S==="google.com"?y=(i=b["google.com"])==null?void 0:i[0]:S==="apple.com"&&(y=(a=b["apple.com"])==null?void 0:a[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",S,"hasProviderSub:",!!y)}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const U=this.crypto.decodeJWT(w);u.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const b=await this.crypto.verifyJWT(w);if(t=b.signatureVerified??!1,!b.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const P=b.payload;s={id:P.sub,email:P.email,signInProvider:S,providerSub:y},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set(Fe,w),E&&await this.storage.set(Ce,E))}else{const U=this.crypto.decodeJWT(g);s={id:U.sub,email:U.email,signInProvider:S,providerSub:y},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}u.log("[CROSSx] 사용자 정보 — id:",s.id);const C=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Le,C),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return u.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new f(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Le);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Fe),n=await this.storage.get(Ce);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Le);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return u.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ce),await this.storage.remove(Le),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new f(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(Fe,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ce,l)}return u.log("[CROSSx] silentRefresh 성공"),c}async executeWithJWT(e,s){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!s)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;u.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(Fe,e),s&&await this.storage.set(Ce,s)),await this.storage.set(Le,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return u.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",o),o==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof f&&o.code===p.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof f&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Gs="crossx_access_token",qs="crossx_refresh_token",Vs="crossx_user_info";class Ks{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(Gs),await this.storage.remove(qs)),await this.storage.remove(Vs)}}class zs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new f(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class At{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let o=0;o<s.length;o++)n[o]=s[o]^t[o];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Js{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new f(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class js{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const We={production:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function Ys(r){const e=r.environment;return e&&e in We?We[e]:null}function Xs(){try{if(typeof window.__CROSSX_CONFIG__<"u"){const r=typeof window.__CROSSX_CONFIG__=="string"?JSON.parse(window.__CROSSX_CONFIG__):window.__CROSSX_CONFIG__,e=Ys(r);if(e)return e}}catch{}return We.production}const Zs=2e3,Rt=6e4,Qs=1e3,er=1e4,tr="0x77359400",Pt="0x3B9ACA00",kt=130,Nt=6,Ot=18,sr=0,rr=30*1e3,ie=class ie extends js{constructor(e,s,t,n,o,i,a,c,l,d,h){var m;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&It(e.logger),this.confirmation=l,this.pinStore=h??new At,this.chainRegistry=d,this.jsonRpc=new Js(d,o),this.signInUseCase=new Ws(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ks(this.internalConfig,t,c),this.migrateWalletUseCase=new zs(t,a),(m=a.setOnUnauthorized)==null||m.call(a,()=>this.forceLogout())}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){console.log("[CROSSx SDK] v1.2.4 초기화 중..."),this.confirmation.setMessages(Tt(this._config.locale));try{const s=Xs();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl;const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){this.applyAuthResult(t);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(n){if(!(n instanceof f&&n.code===p.PIN_CANCELLED))throw n;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(t!=null&&t.success)}),t??null}catch(s){throw new f(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new f(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new f(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...s,address:(n==null?void 0:n.address)??s.address,addresses:t}}catch(t){throw t instanceof f&&t.code===p.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new f(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new f(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new f(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof f&&s.code===p.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof f?s:new f(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.walletProvider.getAddresses(this.userId);return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let s=await this.walletProvider.getAddresses(this.userId);s.length===0&&this.address&&(s=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(s,async()=>{await this.ensurePinForSigning();const n=s.length,i={address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,n))).address,index:n};return s.push(i),i},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof f?e:new f(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof f?s:new f(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Tt(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new f(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof f&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new f(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof f&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new f(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");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 f(p.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof f?i:new f(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new f(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ie.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 f(p.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return ie.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof f?i:new f(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(ie.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=tt(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new f(p.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");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 ie.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof f)throw a;const c=a instanceof Error?a.message:String(a);throw new f(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new f(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 o=tt(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new f(p.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");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 f)throw a;const c=a instanceof Error?a.message:String(a);throw new f(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??Qs,o=er,i=t.timeoutMs??Rt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new f(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var E,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??Zs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??Rt,d=tt(e),h=s.from??"";let m,g;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{m=S;const C=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),U=s.value?BigInt(s.value):0n,b=ie.formatTxAmount(s.value,d.symbol,d.decimals),P=ie.formatTxAmount("0x"+C.toString(16),d.symbol,d.decimals),k=ie.formatTxAmount("0x"+(U+C).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:S.from,to:S.to??s.to,amount:b,fees:P,total:k,nativeSymbol:d.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(g=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:h,to:s.to,amount:ie.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:s.to},w),g)throw g;return{chainId:e,txHash:a,receipt:m}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new f(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof f?n:new f(p.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new f(p.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new f(p.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new f(p.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new f(p.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(p.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:n,formatted:ie.formatWei(n),chainId:e}}catch(t){if(t instanceof f)throw t;const n=t instanceof Error?t.message:String(t);throw new f(p.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const s=BigInt(e);if(s===0n)return"0";const t=10n**BigInt(Ot),n=s/t,i=(s%t).toString().padStart(Ot,"0").replace(/0+$/,"").slice(0,Nt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new St(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof f)throw n;const o=n instanceof Error?n.message:String(n);throw new f(p.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,Nt).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0,o=5,i=null;for(;;){n++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:t,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(l===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyRecoveryPin)==null?void 0:c.call(a,l,e));if(!d){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const h=d.pinStatus;if(o=h.maxAttempts,n=o-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const m=h.lockExpiresAt*1e3,g=Math.max(1,Math.round((m-Date.now())/1e3)),w=g<=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 잠금 — ${g}초, 메시지: ${w}`),await this.confirmation.showRecoveryPinLockedPrompt(g,w),n=0,t="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),t="Incorrect PIN."}catch(d){if(!(d instanceof f))throw d;if(d.code===p.MIGRATION_PIN_LOCKED){const h=d.details;if(o=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const m=((h==null?void 0:h.lockExpiresAt)??0)*1e3,g=Math.max(1,Math.round((m-Date.now())/1e3)),w=g<=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 이미 잠금 — ${g}초`),await this.confirmation.showRecoveryPinLockedPrompt(g,w),n=0,t="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",d),d}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const l=await this.migrateWalletUseCase.execute(i,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof f&&l.code===p.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=Pt;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=tr,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Pt,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=ie.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new f(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new f(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new f(p.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const s=e.domain;if(s==null||typeof s!="object")return;const t=s.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new f(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==kt)throw new f(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${kt} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new f(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new f(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new f(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof f)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=ie.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new f(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new f(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s});if(!i)throw new f(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}const o=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof f){if(c.code===p.PIN_WRONG)return{ok:!1,error:"Incorrect PIN. Please try again."};if(c.code===p.PIN_INVALID)return{ok:!1,error:c.message};if(c.code===p.PIN_LOCKED)return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:(a=c.details)==null?void 0:a.lockExpiresAt}}throw c}}});if(!o)throw new f(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(o),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),t()}catch(o){throw n(o),o}finally{this._verifyPinMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let s,t;try{return await e()}catch(n){if(n instanceof f)if(n.code===p.PIN_WRONG)s="Incorrect PIN. Please enter your current PIN.";else if(n.code===p.PIN_INVALID)s=n.message;else if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked."}else throw n;else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",s),this.pinStore.clear(),await this.ensureVerifiedPin(s,t),t=void 0;try{return await e()}catch(n){if(n instanceof f){if(n.code===p.PIN_WRONG){s="Incorrect PIN. Please try again.";continue}if(n.code===p.PIN_INVALID){s=n.message;continue}if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked.";continue}}throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new f(p.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new f(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new f(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),It(null)}};ie.OFFCHAIN_CHAIN_ID="0";let Ge=ie;class nr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const or="crossx-sdk",ir=1,Ae="data",qe="keys",Ct="aes-primary",ar=12;class Lt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(or,ir);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Ae)||n.createObjectStore(Ae),n.objectStoreNames.contains(qe)||n.createObjectStore(qe)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(qe,Ct);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(qe,Ct,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(ar);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:n}}async decrypt(e){const s=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,s){try{await this.ensureReady();const t=JSON.stringify(s),n=await this.encrypt(t);await this.idbPut(Ae,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Ae,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Ae,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Ae)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}new TextEncoder;const Dt=new TextDecoder,cr=r=>{const e=atob(r),s=new Uint8Array(e.length);for(let t=0;t<e.length;t++)s[t]=e.charCodeAt(t);return s},lr=r=>{let e=r;e instanceof Uint8Array&&(e=Dt.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return cr(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Z extends Error{constructor(e,s){var t;super(e,s),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Z.code="ERR_JOSE_GENERIC";class dr extends Z{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=s}}dr.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class ur extends Z{constructor(e,s,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:s}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=s}}ur.code="ERR_JWT_EXPIRED";class hr extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}hr.code="ERR_JOSE_ALG_NOT_ALLOWED";class pr extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}pr.code="ERR_JOSE_NOT_SUPPORTED";class fr extends Z{constructor(e="decryption operation failed",s){super(e,s),this.code="ERR_JWE_DECRYPTION_FAILED"}}fr.code="ERR_JWE_DECRYPTION_FAILED";class _r extends Z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}_r.code="ERR_JWE_INVALID";class xr extends Z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}xr.code="ERR_JWS_INVALID";class me extends Z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}me.code="ERR_JWT_INVALID";class gr extends Z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}gr.code="ERR_JWK_INVALID";class mr extends Z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}mr.code="ERR_JWKS_INVALID";class wr extends Z{constructor(e="no applicable key found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_NO_MATCHING_KEY"}}wr.code="ERR_JWKS_NO_MATCHING_KEY";class yr extends Z{constructor(e="multiple matching keys found in the JSON Web Key Set",s){super(e,s),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}yr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class br extends Z{constructor(e="request timed out",s){super(e,s),this.code="ERR_JWKS_TIMEOUT"}}br.code="ERR_JWKS_TIMEOUT";class vr extends Z{constructor(e="signature verification failed",s){super(e,s),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}vr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function Sr(r){return typeof r=="object"&&r!==null}function Ir(r){if(!Sr(r)||Object.prototype.toString.call(r)!=="[object Object]")return!1;if(Object.getPrototypeOf(r)===null)return!0;let e=r;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(r)===e}const Er=lr;function Tr(r){if(typeof r!="string")throw new me("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:s}=r.split(".");if(s===5)throw new me("Only JWTs using Compact JWS serialization can be decoded");if(s!==3)throw new me("Invalid JWT");if(!e)throw new me("JWTs must contain a payload");let t;try{t=Er(e)}catch{throw new me("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Dt.decode(t))}catch{throw new me("Failed to parse the decoded payload as JSON")}if(!Ir(n))throw new me("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function st(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function fe(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function K(r,e,s=""){const t=st(r),n=r==null?void 0:r.length,o=e!==void 0;if(!t||o&&n!==e){const i=s&&`"${s}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof r}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return r}function Mt(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");fe(r.outputLen),fe(r.blockLen)}function Re(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function $t(r,e){K(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function Ar(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Pe(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function rt(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function he(r,e){return r<<32-e|r>>>e}const Rr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Pr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function kr(r){for(let e=0;e<r.length;e++)r[e]=Pr(r[e]);return r}const Bt=Rr?r=>r:kr,Ut=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Nr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function De(r){if(K(r),Ut)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=Nr[r[s]];return e}const _e={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ht(r){if(r>=_e._0&&r<=_e._9)return r-_e._0;if(r>=_e.A&&r<=_e.F)return r-(_e.A-10);if(r>=_e.a&&r<=_e.f)return r-(_e.a-10)}function Ve(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(Ut)return Uint8Array.fromHex(r);const e=r.length,s=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(s);for(let n=0,o=0;n<s;n++,o+=2){const i=Ht(r.charCodeAt(o)),a=Ht(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function we(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];K(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function Ft(r,e={}){const s=(n,o)=>r(o).update(n).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=n=>r(n),Object.assign(s,e),Object.freeze(s)}function Wt(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const Or=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function Cr(r,e,s){return r&e^~r&s}function Lr(r,e,s){return r&e^r&s^e&s}class Dr{constructor(e,s,t,n){I(this,"blockLen");I(this,"outputLen");I(this,"padOffset");I(this,"isLE");I(this,"buffer");I(this,"view");I(this,"finished",!1);I(this,"length",0);I(this,"pos",0);I(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=rt(this.buffer)}update(e){Re(this),K(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=rt(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(s,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Re(this),$t(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,Pe(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let h=i;h<n;h++)s[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=rt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],o)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const ye=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ke=BigInt(2**32-1),Gt=BigInt(32);function Mr(r,e=!1){return e?{h:Number(r&Ke),l:Number(r>>Gt&Ke)}:{h:Number(r>>Gt&Ke)|0,l:Number(r&Ke)|0}}function $r(r,e=!1){const s=r.length;let t=new Uint32Array(s),n=new Uint32Array(s);for(let o=0;o<s;o++){const{h:i,l:a}=Mr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const Br=(r,e,s)=>r<<s|e>>>32-s,Ur=(r,e,s)=>e<<s|r>>>32-s,Hr=(r,e,s)=>e<<s-32|r>>>64-s,Fr=(r,e,s)=>r<<s-32|e>>>64-s,Wr=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),be=new Uint32Array(64);class Gr extends Dr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,s,t,n,o,i,a,c]}set(e,s,t,n,o,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let h=0;h<16;h++,s+=4)be[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const m=be[h-15],g=be[h-2],w=he(m,7)^he(m,18)^m>>>3,E=he(g,17)^he(g,19)^g>>>10;be[h]=E+be[h-7]+w+be[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){const m=he(a,6)^he(a,11)^he(a,25),g=d+m+Cr(a,c,l)+Wr[h]+be[h]|0,E=(he(t,2)^he(t,13)^he(t,22))+Lr(t,n,o)|0;d=l,l=c,c=a,a=i+g|0,i=o,o=n,n=t,t=g+E|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){Pe(be)}destroy(){this.set(0,0,0,0,0,0,0,0),Pe(this.buffer)}}class qr extends Gr{constructor(){super(32);I(this,"A",ye[0]|0);I(this,"B",ye[1]|0);I(this,"C",ye[2]|0);I(this,"D",ye[3]|0);I(this,"E",ye[4]|0);I(this,"F",ye[5]|0);I(this,"G",ye[6]|0);I(this,"H",ye[7]|0)}}const Vr=Ft(()=>new qr,Or(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const nt=BigInt(0),ot=BigInt(1);function ze(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function qt(r){if(typeof r=="bigint"){if(!Ye(r))throw new Error("positive bigint expected, got "+r)}else fe(r);return r}function Je(r){const e=qt(r).toString(16);return e.length&1?"0"+e:e}function Vt(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?nt:BigInt("0x"+r)}function je(r){return Vt(De(r))}function Kt(r){return Vt(De(Kr(K(r)).reverse()))}function it(r,e){fe(e),r=qt(r);const s=Ve(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function zt(r,e){return it(r,e).reverse()}function Kr(r){return Uint8Array.from(r)}const Ye=r=>typeof r=="bigint"&&nt<=r;function zr(r,e,s){return Ye(r)&&Ye(e)&&Ye(s)&&e<=r&&r<s}function Jr(r,e,s,t){if(!zr(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function jr(r){let e;for(e=0;r>nt;r>>=ot,e+=1);return e}const at=r=>(ot<<BigInt(r))-ot;function Yr(r,e,s){if(fe(r,"hashLen"),fe(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const h=()=>{c.fill(1),l.fill(0),d=0},m=(...y)=>s(l,we(c,...y)),g=(y=n)=>{l=m(o,y),c=m(),y.length!==0&&(l=m(i,y),c=m())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const S=[];for(;y<e;){c=m();const C=c.slice();S.push(C),y+=c.length}return we(...S)};return(y,S)=>{h(),g(y);let C;for(;!(C=S(w()));)g();return h(),C}}function ct(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(o,i,a){const c=r[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(s,!0)}function Jt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oe=BigInt(0),Q=BigInt(1),Ie=BigInt(2),jt=BigInt(3),Yt=BigInt(4),Xt=BigInt(5),Xr=BigInt(7),Zt=BigInt(8),Zr=BigInt(9),Qt=BigInt(16);function ue(r,e){const s=r%e;return s>=oe?s:e+s}function le(r,e,s){let t=r;for(;e-- >oe;)t*=t,t%=s;return t}function es(r,e){if(r===oe)throw new Error("invert: expected non-zero number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let s=ue(r,e),t=e,n=oe,o=Q;for(;s!==oe;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==Q)throw new Error("invert: does not exist");return ue(n,e)}function lt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function ts(r,e){const s=(r.ORDER+Q)/Yt,t=r.pow(e,s);return lt(r,t,e),t}function Qr(r,e){const s=(r.ORDER-Xt)/Zt,t=r.mul(e,Ie),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,Ie),n),a=r.mul(o,r.sub(i,r.ONE));return lt(r,a,e),a}function en(r){const e=Xe(r),s=ss(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Xr)/Qt;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const h=a.mul(l,n),m=a.mul(l,o),g=a.eql(a.sqr(d),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,d,g),d=a.cmov(m,h,w);const E=a.eql(a.sqr(d),c),y=a.cmov(l,d,E);return lt(a,y,c),y}}function ss(r){if(r<jt)throw new Error("sqrt is not defined for small field");let e=r-Q,s=0;for(;e%Ie===oe;)e/=Ie,s++;let t=Ie;const n=Xe(r);for(;ns(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return ts;let o=n.pow(t,e);const i=(e+Q)/Ie;return function(c,l){if(c.is0(l))return l;if(ns(c,l)!==1)throw new Error("Cannot find square root");let d=s,h=c.mul(c.ONE,o),m=c.pow(l,e),g=c.pow(l,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let w=1,E=c.sqr(m);for(;!c.eql(E,c.ONE);)if(w++,E=c.sqr(E),w===d)throw new Error("Cannot find square root");const y=Q<<BigInt(d-w-1),S=c.pow(h,y);d=w,h=c.sqr(S),m=c.mul(m,h),g=c.mul(g,S)}return g}}function tn(r){return r%Yt===jt?ts:r%Zt===Xt?Qr:r%Qt===Zr?en(r):ss(r)}const sn=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function rn(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=sn.reduce((t,n)=>(t[n]="function",t),e);return ct(r,s),r}function nn(r,e,s){if(s<oe)throw new Error("invalid exponent, negatives unsupported");if(s===oe)return r.ONE;if(s===Q)return e;let t=r.ONE,n=e;for(;s>oe;)s&Q&&(t=r.mul(t,n)),n=r.sqr(n),s>>=Q;return t}function rs(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),n=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),o=r.inv(n);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),o),t}function ns(r,e){const s=(r.ORDER-Q)/Ie,t=r.pow(e,s),n=r.eql(t,r.ONE),o=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function on(r,e){e!==void 0&&fe(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class an{constructor(e,s={}){I(this,"ORDER");I(this,"BITS");I(this,"BYTES");I(this,"isLE");I(this,"ZERO",oe);I(this,"ONE",Q);I(this,"_lengths");I(this,"_sqrt");I(this,"_mod");var i;if(e<=oe)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=on(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ue(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Q)===Q}neg(e){return ue(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ue(e*e,this.ORDER)}add(e,s){return ue(e+s,this.ORDER)}sub(e,s){return ue(e-s,this.ORDER)}mul(e,s){return ue(e*s,this.ORDER)}pow(e,s){return nn(this,e,s)}div(e,s){return ue(e*es(s,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,s){return e+s}subN(e,s){return e-s}mulN(e,s){return e*s}inv(e){return es(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=tn(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?zt(e,this.BYTES):it(e,this.BYTES)}fromBytes(e,s=!1){K(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?Kt(e):je(e);if(a&&(c=ue(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return rs(this,e)}cmov(e,s,t){return t?s:e}}function Xe(r,e={}){return new an(r,e)}function os(r){if(typeof r!="bigint")throw new Error("field order must be bigint");const e=r.toString(2).length;return Math.ceil(e/8)}function is(r){const e=os(r);return e+Math.ceil(e/2)}function cn(r,e,s=!1){K(r);const t=r.length,n=os(e),o=is(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?Kt(r):je(r),a=ue(i,e-Q)+Q;return s?zt(a,n):it(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ke=BigInt(0),Ee=BigInt(1);function Ze(r,e){const s=e.negate();return r?s:e}function as(r,e){const s=rs(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function cs(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function dt(r,e){cs(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=at(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function ls(r,e,s){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=s;let a=Number(r&n),c=r>>i;a>t&&(a-=o,c+=Ee);const l=e*t,d=l+Math.abs(a)-1,h=a===0,m=a<0,g=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:m,isNegF:g,offsetF:l}}const ut=new WeakMap,ds=new WeakMap;function ht(r){return ds.get(r)||1}function us(r){if(r!==ke)throw new Error("invalid wNAF")}class ln{constructor(e,s){I(this,"BASE");I(this,"ZERO");I(this,"Fn");I(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>ke;)s&Ee&&(t=t.add(n)),n=n.double(),s>>=Ee;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=dt(s,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=dt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:m,offsetF:g}=ls(t,a,i);t=c,d?o=o.add(Ze(m,s[g])):n=n.add(Ze(h,s[l]))}return us(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=dt(e,this.bits);for(let i=0;i<o.windows&&t!==ke;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=ls(t,i,o);if(t=a,!l){const h=s[c];n=n.add(d?h.negate():h)}}return us(t),n}getPrecomputes(e,s,t){let n=ut.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),ut.set(s,n))),n}cached(e,s,t){const n=ht(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=ht(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){cs(s,this.bits),ds.set(e,s),ut.delete(e)}hasCache(e){return ht(e)!==1}}function dn(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>ke||t>ke;)s&Ee&&(o=o.add(n)),t&Ee&&(i=i.add(n)),n=n.double(),s>>=Ee,t>>=Ee;return{p1:o,p2:i}}function hs(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return rn(e),e}else return Xe(r,{isLE:s})}function un(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>ke))throw new Error(`CURVE.${c} must be positive bigint`)}const n=hs(e.p,s.Fp,t),o=hs(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function hn(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class ps{constructor(e,s){I(this,"oHash");I(this,"iHash");I(this,"blockLen");I(this,"outputLen");I(this,"finished",!1);I(this,"destroyed",!1);if(Mt(e),K(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Pe(n)}update(e){return Re(this),this.iHash.update(e),this}digestInto(e){Re(this),K(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const fs=(r,e,s)=>new ps(r,e).update(s).digest();fs.create=(r,e)=>new ps(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _s=(r,e)=>(r+(r>=0?e:-e)/xs)/e;function pn(r,e,s){const[[t,n],[o,i]]=e,a=_s(i*r,s),c=_s(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const h=l<xe,m=d<xe;h&&(l=-l),m&&(d=-d);const g=at(Math.ceil(jr(s)/2))+Ne;if(l<xe||l>=g||d<xe||d>=g)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:m,k2:d}}function pt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ft(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ze(s.lowS,"lowS"),ze(s.prehash,"prehash"),s.format!==void 0&&pt(s.format),s}class fn extends Error{constructor(e=""){super(e)}}const ve={Err:fn,_tlv:{encode:(r,e)=>{const{Err:s}=ve;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=Je(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?Je(n.length/2|128):"";return Je(r)+o+n+e},decode(r,e){const{Err:s}=ve;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ve;if(r<xe)throw new e("integer: negative integers are not allowed");let s=Je(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=ve;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return je(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ve,n=K(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ve,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},xe=BigInt(0),Ne=BigInt(1),xs=BigInt(2),Qe=BigInt(3),_n=BigInt(4);function xn(r,e={}){const s=un("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;ct(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ms(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(N,_,x){const{x:v,y:A}=_.toAffine(),L=t.toBytes(v);if(ze(x,"isCompressed"),x){d();const O=!t.isOdd(A);return we(gs(O),L)}else return we(Uint8Array.of(4),L,t.toBytes(A))}function m(N){K(N,void 0,"Point");const{publicKey:_,publicKeyUncompressed:x}=l,v=N.length,A=N[0],L=N.subarray(1);if(v===_&&(A===2||A===3)){const O=t.fromBytes(L);if(!t.isValid(O))throw new Error("bad point: is not on curve, wrong x");const M=E(O);let T;try{T=t.sqrt(M)}catch(Y){const V=Y instanceof Error?": "+Y.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const $=t.isOdd(T);return(A&1)===1!==$&&(T=t.neg(T)),{x:O,y:T}}else if(v===x&&A===4){const O=t.BYTES,M=t.fromBytes(L.subarray(0,O)),T=t.fromBytes(L.subarray(O,O*2));if(!y(M,T))throw new Error("bad point: is not on curve");return{x:M,y:T}}else throw new Error(`bad point: got length ${v}, expected compressed=${_} or uncompressed=${x}`)}const g=e.toBytes||h,w=e.fromBytes||m;function E(N){const _=t.sqr(N),x=t.mul(_,N);return t.add(t.add(x,t.mul(N,o.a)),o.b)}function y(N,_){const x=t.sqr(_),v=E(N);return t.eql(x,v)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const S=t.mul(t.pow(o.a,Qe),_n),C=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(S,C)))throw new Error("bad curve params: a or b");function U(N,_,x=!1){if(!t.isValid(_)||x&&t.is0(_))throw new Error(`bad point coordinate ${N}`);return _}function b(N){if(!(N instanceof G))throw new Error("Weierstrass Point expected")}function P(N){if(!c||!c.basises)throw new Error("no endo");return pn(N,c.basises,n.ORDER)}const k=Jt((N,_)=>{const{X:x,Y:v,Z:A}=N;if(t.eql(A,t.ONE))return{x,y:v};const L=N.is0();_==null&&(_=L?t.ONE:t.inv(A));const O=t.mul(x,_),M=t.mul(v,_),T=t.mul(A,_);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:O,y:M}}),W=Jt(N=>{if(N.is0()){if(e.allowInfinityPoint&&!t.is0(N.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:x}=N.toAffine();if(!t.isValid(_)||!t.isValid(x))throw new Error("bad point: x or y not field elements");if(!y(_,x))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function z(N,_,x,v,A){return x=new G(t.mul(x.X,N),x.Y,x.Z),_=Ze(v,_),x=Ze(A,x),_.add(x)}const R=class R{constructor(_,x,v){I(this,"X");I(this,"Y");I(this,"Z");this.X=U("x",_),this.Y=U("y",x,!0),this.Z=U("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){const{x,y:v}=_||{};if(!_||!t.isValid(x)||!t.isValid(v))throw new Error("invalid affine point");if(_ instanceof R)throw new Error("projective point not allowed");return t.is0(x)&&t.is0(v)?R.ZERO:new R(x,v,t.ONE)}static fromBytes(_){const x=R.fromAffine(w(K(_,void 0,"point")));return x.assertValidity(),x}static fromHex(_){return R.fromBytes(Ve(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,x=!0){return D.createCache(this,_),x||this.multiply(Qe),this}assertValidity(){W(this)}hasEvenY(){const{y:_}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(_)}equals(_){b(_);const{X:x,Y:v,Z:A}=this,{X:L,Y:O,Z:M}=_,T=t.eql(t.mul(x,M),t.mul(L,A)),$=t.eql(t.mul(v,M),t.mul(O,A));return T&&$}negate(){return new R(this.X,t.neg(this.Y),this.Z)}double(){const{a:_,b:x}=o,v=t.mul(x,Qe),{X:A,Y:L,Z:O}=this;let M=t.ZERO,T=t.ZERO,$=t.ZERO,F=t.mul(A,A),Y=t.mul(L,L),V=t.mul(O,O),H=t.mul(A,L);return H=t.add(H,H),$=t.mul(A,O),$=t.add($,$),M=t.mul(_,$),T=t.mul(v,V),T=t.add(M,T),M=t.sub(Y,T),T=t.add(Y,T),T=t.mul(M,T),M=t.mul(H,M),$=t.mul(v,$),V=t.mul(_,V),H=t.sub(F,V),H=t.mul(_,H),H=t.add(H,$),$=t.add(F,F),F=t.add($,F),F=t.add(F,V),F=t.mul(F,H),T=t.add(T,F),V=t.mul(L,O),V=t.add(V,V),F=t.mul(V,H),M=t.sub(M,F),$=t.mul(V,Y),$=t.add($,$),$=t.add($,$),new R(M,T,$)}add(_){b(_);const{X:x,Y:v,Z:A}=this,{X:L,Y:O,Z:M}=_;let T=t.ZERO,$=t.ZERO,F=t.ZERO;const Y=o.a,V=t.mul(o.b,Qe);let H=t.mul(x,L),X=t.mul(v,O),se=t.mul(A,M),ce=t.add(x,v),J=t.add(L,O);ce=t.mul(ce,J),J=t.add(H,X),ce=t.sub(ce,J),J=t.add(x,A);let re=t.add(L,M);return J=t.mul(J,re),re=t.add(H,se),J=t.sub(J,re),re=t.add(v,A),T=t.add(O,M),re=t.mul(re,T),T=t.add(X,se),re=t.sub(re,T),F=t.mul(Y,J),T=t.mul(V,se),F=t.add(T,F),T=t.sub(X,F),F=t.add(X,F),$=t.mul(T,F),X=t.add(H,H),X=t.add(X,H),se=t.mul(Y,se),J=t.mul(V,J),X=t.add(X,se),se=t.sub(H,se),se=t.mul(Y,se),J=t.add(J,se),H=t.mul(X,J),$=t.add($,H),H=t.mul(re,J),T=t.mul(ce,T),T=t.sub(T,H),H=t.mul(ce,X),F=t.mul(re,F),F=t.add(F,H),new R(T,$,F)}subtract(_){return this.add(_.negate())}is0(){return this.equals(R.ZERO)}multiply(_){const{endo:x}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let v,A;const L=O=>D.cached(this,O,M=>as(R,M));if(x){const{k1neg:O,k1:M,k2neg:T,k2:$}=P(_),{p:F,f:Y}=L(M),{p:V,f:H}=L($);A=Y.add(H),v=z(x.beta,F,V,O,T)}else{const{p:O,f:M}=L(_);v=O,A=M}return as(R,[v,A])[0]}multiplyUnsafe(_){const{endo:x}=e,v=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===xe||v.is0())return R.ZERO;if(_===Ne)return v;if(D.hasCache(this))return this.multiply(_);if(x){const{k1neg:A,k1:L,k2neg:O,k2:M}=P(_),{p1:T,p2:$}=dn(R,v,L,M);return z(x.beta,T,$,A,O)}else return D.unsafe(v,_)}toAffine(_){return k(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return i===Ne?!0:_?_(R,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return i===Ne?this:_?_(R,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(_=!0){return ze(_,"isCompressed"),this.assertValidity(),g(R,this,_)}toHex(_=!0){return De(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};I(R,"BASE",new R(o.Gx,o.Gy,t.ONE)),I(R,"ZERO",new R(t.ZERO,t.ONE,t.ZERO)),I(R,"Fp",t),I(R,"Fn",n);let G=R;const q=n.BITS,D=new ln(G,e.endo?Math.ceil(q/2):q);return G.BASE.precompute(8),G}function gs(r){return Uint8Array.of(r?2:3)}function ms(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function gn(r,e={}){const{Fn:s}=r,t=e.randomBytes||Wt,n=Object.assign(ms(r.Fp,s),{seed:is(s.ORDER)});function o(g){try{const w=s.fromBytes(g);return s.isValidNot0(w)}catch{return!1}}function i(g,w){const{publicKey:E,publicKeyUncompressed:y}=n;try{const S=g.length;return w===!0&&S!==E||w===!1&&S!==y?!1:!!r.fromBytes(g)}catch{return!1}}function a(g=t(n.seed)){return cn(K(g,n.seed,"seed"),s.ORDER)}function c(g,w=!0){return r.BASE.multiply(s.fromBytes(g)).toBytes(w)}function l(g){const{secretKey:w,publicKey:E,publicKeyUncompressed:y}=n;if(!st(g)||"_lengths"in s&&s._lengths||w===E)return;const S=K(g,void 0,"key").length;return S===E||S===y}function d(g,w,E=!0){if(l(g)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(g);return r.fromBytes(w).multiply(y).toBytes(E)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=hn(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:h,lengths:n})}function mn(r,e,s={}){Mt(e),ct(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||Wt,n=s.hmac||((_,x)=>fs(e,_,x)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:g}=gn(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=a*xs<o.ORDER;function y(_){const x=a>>Ne;return _>x}function S(_,x){if(!i.isValidNot0(x))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return x}function C(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(_,x){pt(x);const v=g.signature,A=x==="compact"?v:x==="recovered"?v+1:void 0;return K(_,A)}class b{constructor(x,v,A){I(this,"r");I(this,"s");I(this,"recovery");if(this.r=S("r",x),this.s=S("s",v),A!=null){if(C(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(x,v=w.format){U(x,v);let A;if(v==="der"){const{r:T,s:$}=ve.toSig(K(x));return new b(T,$)}v==="recovered"&&(A=x[0],v="compact",x=x.subarray(1));const L=g.signature/2,O=x.subarray(0,L),M=x.subarray(L,L*2);return new b(i.fromBytes(O),i.fromBytes(M),A)}static fromHex(x,v){return this.fromBytes(Ve(x),v)}assertRecovery(){const{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new b(this.r,this.s,x)}recoverPublicKey(x){const{r:v,s:A}=this,L=this.assertRecovery(),O=L===2||L===3?v+a:v;if(!o.isValid(O))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(O),T=r.fromBytes(we(gs((L&1)===0),M)),$=i.inv(O),F=k(K(x,void 0,"msgHash")),Y=i.create(-F*$),V=i.create(A*$),H=r.BASE.multiplyUnsafe(Y).add(T.multiplyUnsafe(V));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(x=w.format){if(pt(x),x==="der")return Ve(ve.hexFromSig(this));const{r:v,s:A}=this,L=i.toBytes(v),O=i.toBytes(A);return x==="recovered"?(C(),we(Uint8Array.of(this.assertRecovery()),L,O)):we(L,O)}toHex(x){return De(this.toBytes(x))}}const P=s.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");const v=je(x),A=x.length*8-c;return A>0?v>>BigInt(A):v},k=s.bits2int_modN||function(x){return i.create(P(x))},W=at(c);function z(_){return Jr("num < 2^"+c,_,xe,W),i.toBytes(_)}function G(_,x){return K(_,void 0,"message"),x?K(e(_),void 0,"prehashed message"):_}function q(_,x,v){const{lowS:A,prehash:L,extraEntropy:O}=ft(v,w);_=G(_,L);const M=k(_),T=i.fromBytes(x);if(!i.isValidNot0(T))throw new Error("invalid private key");const $=[z(T),z(M)];if(O!=null&&O!==!1){const H=O===!0?t(g.secretKey):O;$.push(K(H,void 0,"extraEntropy"))}const F=we(...$),Y=M;function V(H){const X=P(H);if(!i.isValidNot0(X))return;const se=i.inv(X),ce=r.BASE.multiply(X).toAffine(),J=i.create(ce.x);if(J===xe)return;const re=i.create(se*i.create(Y+J*T));if(re===xe)return;let Ds=(ce.x===J?0:2)|Number(ce.y&Ne),Ms=re;return A&&y(re)&&(Ms=i.neg(re),Ds^=1),new b(J,Ms,E?void 0:Ds)}return{seed:F,k2sig:V}}function D(_,x,v={}){const{seed:A,k2sig:L}=q(_,x,v);return Yr(e.outputLen,i.BYTES,n)(A,L).toBytes(v.format)}function R(_,x,v,A={}){const{lowS:L,prehash:O,format:M}=ft(A,w);if(v=K(v,void 0,"publicKey"),x=G(x,O),!st(_)){const T=_ instanceof b?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}U(_,M);try{const T=b.fromBytes(_,M),$=r.fromBytes(v);if(L&&T.hasHighS())return!1;const{r:F,s:Y}=T,V=k(x),H=i.inv(Y),X=i.create(V*H),se=i.create(F*H),ce=r.BASE.multiplyUnsafe(X).add($.multiplyUnsafe(se));return ce.is0()?!1:i.create(ce.x)===F}catch{return!1}}function N(_,x,v={}){const{prehash:A}=ft(v,w);return x=G(x,A),b.fromBytes(_,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:g,Point:r,sign:D,verify:R,recoverPublicKey:N,Signature:b,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _t={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},wn={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ws=BigInt(2);function yn(r){const e=_t.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,h=le(d,s,e)*d%e,m=le(h,s,e)*d%e,g=le(m,ws,e)*l%e,w=le(g,n,e)*g%e,E=le(w,o,e)*w%e,y=le(E,a,e)*E%e,S=le(y,c,e)*y%e,C=le(S,a,e)*E%e,U=le(C,s,e)*d%e,b=le(U,i,e)*w%e,P=le(b,t,e)*l%e,k=le(P,ws,e);if(!xt.eql(xt.sqr(k),r))throw new Error("Cannot find square root");return k}const xt=Xe(_t.p,{sqrt:yn}),bn=mn(xn(_t,{Fp:xt,endo:wn}),Vr),vn=BigInt(0),Me=BigInt(1),Sn=BigInt(2),In=BigInt(7),En=BigInt(256),Tn=BigInt(113),ys=[],bs=[],vs=[];for(let r=0,e=Me,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ys.push(2*(5*t+s)),bs.push((r+1)*(r+2)/2%64);let n=vn;for(let o=0;o<7;o++)e=(e<<Me^(e>>In)*Tn)%En,e&Sn&&(n^=Me<<(Me<<BigInt(o))-Me);vs.push(n)}const Ss=$r(vs,!0),An=Ss[0],Rn=Ss[1],Is=(r,e,s)=>s>32?Hr(r,e,s):Br(r,e,s),Es=(r,e,s)=>s>32?Fr(r,e,s):Ur(r,e,s);function Pn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],d=s[c+1],h=Is(l,d,1)^s[a],m=Es(l,d,1)^s[a+1];for(let g=0;g<50;g+=10)r[i+g]^=h,r[i+g+1]^=m}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=bs[i],c=Is(n,o,a),l=Es(n,o,a),d=ys[i];n=r[d],o=r[d+1],r[d]=c,r[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=An[t],r[1]^=Rn[t]}Pe(s)}class gt{constructor(e,s,t,n=!1,o=24){I(this,"state");I(this,"pos",0);I(this,"posOut",0);I(this,"finished",!1);I(this,"state32");I(this,"destroyed",!1);I(this,"blockLen");I(this,"suffix");I(this,"outputLen");I(this,"enableXOF",!1);I(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,fe(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ar(this.state)}clone(){return this._cloneInto()}keccak(){Bt(this.state32),Pn(this.state32,this.rounds),Bt(this.state32),this.posOut=0,this.pos=0}update(e){Re(this),K(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Re(this,!1),K(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return fe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($t(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Pe(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new gt(s,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const Ts=((r,e,s,t={})=>Ft(()=>new gt(e,r,s),t))(1,136,32);class kn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Tr(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
2
|
-
${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=Ts(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Nn(a),l=c.slice(0,32),d=c.slice(32,64),h=c[64],m=h>=27?h-27:h,E=new bn.Signature(As(l),As(d)).addRecoveryBit(m).recoverPublicKey(i).toBytes(!1).slice(1),y=Ts(E);return"0x"+De(y.slice(12))}}function Nn(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function As(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const On=3e4;class Cn{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??On);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}class Te{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=Te.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n==="")throw u.error("[CROSSx] nonce claim 누락 — JWT payload 전체 키 목록:",Object.keys(t)),u.error("[CROSSx] 원인 추정: OAuth 서버가 Google/Apple 인증 요청에 nonce 파라미터를 포함하지 않았을 수 있습니다.","서버 로그에서 /auth/google, /auth/apple 요청 URL에 nonce 쿼리가 있는지 확인하세요."),new Error("ID Token에 nonce claim이 없습니다 — OAuth 서버 설정을 확인해 주세요");if(o.includes("appleid.apple.com")){const i=await Te.sha256Hex(s);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Te.generateRandom16Hex(),l=Te.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const m=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!m){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const g=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),b(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,E=30;let y=0,S=null;const C=()=>{clearInterval(U),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),S=setTimeout(()=>{b(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},U=setInterval(()=>{y++;try{m.closed&&(y<=w?C():(b(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),b=()=>{clearTimeout(g),clearInterval(U),S&&clearTimeout(S),window.removeEventListener("message",P)},P=k=>{var z,G,q,D,R;if(k.origin!==e.expectedOrigin)return;b(),u.log("[CROSSx] OAuth postMessage 수신 — status:",k.data.status);const W=k.data.state??((z=k.data.data)==null?void 0:z.state);if(!W||W!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(k.data.status==="success"){const N=(G=k.data.data)==null?void 0:G.idToken,_=(q=k.data.data)==null?void 0:q.accessToken,x=_??N;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!_,hasIdToken:!!N}),!x){u.error("[CROSSx] 토큰을 찾을 수 없음:",k.data),t(new Error("Token not found in response"));return}N?Te.verifyIdTokenNonce(N,l).then(()=>s(x)).catch(v=>{u.error("[CROSSx] nonce 검증 실패:",v),t(v instanceof Error?v:new Error("nonce verification failed"))}):s(x)}else u.error("[CROSSx] OAuth 실패:",(D=k.data.data)==null?void 0:D.error),t(new Error(((R=k.data.data)==null?void 0:R.error)||"Authentication failed"))};window.addEventListener("message",P)})}}const $e="crossx_wallet_data",Oe="crossx_mock_pin_hash";class Ln{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get($e)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get($e);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set($e,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Oe,o),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new f(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get($e);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,s,t,n=0,o,i){return u.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return u.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){u.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return u.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Oe);return s&&s!==e?!1:(s||await this.storage.set(Oe,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new f(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Oe);if(n&&t&&n!==t)throw new f(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Oe,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new f(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new f(p.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set($e,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Oe,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Be{constructor(e,s,t,n,o){this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=n,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new f(p.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const h=d.message||d.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:h,url:o,method:e});const m=Be.mapGatewayError(d.code,d.data),g=Be.getGatewayErrorMessage(d.code,h),w=d.data,E=m===p.PIN_LOCKED?Be.extractLockDetails(w):w??void 0,y=new f(m,g,E);throw y.gatewayCode=d.code,y.gatewayMessage=h,m===p.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(u.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof f)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,h=d.message||d.data||"API 요청에 실패했습니다",m=d.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:m,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new f(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${m}): ${h}`)}throw l}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new f(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new f(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new f(p.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new f(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async migrateWallet(e,s){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).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 f(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??e,t=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);return t?{lockExpiresAt:t>1e10?t:t*1e3}:{}}static mapGatewayError(e,s){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10028:return p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Invalid PIN format. Please enter a 6-digit numeric PIN.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";default:return`Request failed (${e}): ${s}`}}}class Ue{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=Ue.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?rr:sr;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new f(Ue.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Ue.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new f(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(He).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.APP_IDENTIFIER_MISSING;case-10025:return p.INVALID_APP_TYPE;default:return p.UNKNOWN_ERROR}}}const Rs="__crossx-confirm-style",ee="__crossx-confirm-overlay",Dn={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function Ps(r,e){const s=Dn[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const Mn=`
|
|
1
|
+
var CROSSx=function(oe){"use strict";var Di=Object.defineProperty;var Mi=(oe,f,x)=>f in oe?Di(oe,f,{enumerable:!0,configurable:!0,writable:!0,value:x}):oe[f]=x;var A=(oe,f,x)=>Mi(oe,typeof f!="symbol"?f+"":f,x);var _t,Ps;var f=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_CANCELLED="PIN_CANCELLED",s.PIN_LOCKED="PIN_LOCKED",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(f||{});class x extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const Ze={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Ns=Object.fromEntries(Object.entries(Ze).map(([s,e])=>[s,e.caipId])),ks=new Map(Object.values(Ze).map(s=>[s.caipId,s]));new Map(Object.values(Ze).map(s=>[s.chainId,s]));const Ls={symbol:"",decimals:18};function gt(s){var e;return((e=ks.get(s))==null?void 0:e.nativeCurrency)??Ls}class zt{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new x(f.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(f.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let Oe=null;function $i(s){}function Yt(s){Oe=s}const u={log(...s){if(Oe){Oe.log(...s);return}},warn(...s){if(Oe){Oe.warn(...s);return}},error(...s){if(Oe){Oe.error(...s);return}}},Ds={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간"},jt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from"},Ms={ko:Ds,en:jt};function Zt(s="en",e){return Ms[s]??jt}const Xt="crossx_access_token",Qt="crossx_refresh_token",er="crossx_user_info";class $s{constructor(e,r,t,n,o,i,a){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,r){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new x(f.AUTH_FAILED,`${r} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new x(f.AUTH_FAILED,`${r} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let r,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:h}=this.config,w=`${d}${l}`;u.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const p=await this.oauth.openAuth({authUrl:w,expectedOrigin:new URL(d).origin});u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",p.length,")");const{accessToken:m,refreshToken:v}=await this.exchangeFirebaseToken(p,h);let y,E;try{const B=this.crypto.decodeJWT(p);E=(n=B.firebase)==null?void 0:n.sign_in_provider;const b=((o=B.firebase)==null?void 0:o.identities)??{};E==="google.com"?y=(i=b["google.com"])==null?void 0:i[0]:E==="apple.com"&&(y=(a=b["apple.com"])==null?void 0:a[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",E,"hasProviderSub:",!!y)}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(m){const B=this.crypto.decodeJWT(m);u.log("[CROSSx] access_token 디코딩 — sub:",B.sub,"exp:",B.exp);const b=await this.crypto.verifyJWT(m);if(t=b.signatureVerified??!1,!b.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const P=b.payload;r={id:P.sub,email:P.email,signInProvider:E,providerSub:y},this.tokenStore.set(m),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,m),v&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,v):v&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const B=this.crypto.decodeJWT(p);r={id:B.sub,email:B.email,signInProvider:E,providerSub:y},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",r.id)}u.log("[CROSSx] 사용자 정보 — id:",r.id);const k=this.useCookieAuth?{id:r.id,signInProvider:r.signInProvider,providerSub:r.providerSub}:r;await this.storage.set(this.STORAGE_KEY_USER,k),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return u.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",r.id),this.loadWallet(r,t)}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(f.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return 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 o=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const r=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){return u.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new x(f.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,c);const l=this.extractRefreshToken(a);l&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,l)}return u.log("[CROSSx] silentRefresh 성공"),c}async executeWithJWT(e,r){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!r)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;u.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return u.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(er);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(Xt);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Qt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(er),await this.storage.remove(Xt),await this.storage.remove(Qt),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",o),o==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof x&&o.code===f.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===f.PROJECT_NOT_REGISTERED||o.code===f.PROJECT_ID_MISSING||o.code===f.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}}class Ws{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Bs{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new x(f.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class tr{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let o=0;o<r.length;o++)n[o]=r[o]^t[o];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Us{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new x(f.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Hs{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}var Xe={environment:"production"};const Qe={production:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function Fs(s){const e=s.environment;return e&&e in Qe?Qe[e]:null}function Ks(){try{if(typeof Xe<"u"){const s=typeof Xe=="string"?JSON.parse(Xe):Xe,e=Fs(s);if(e)return e}}catch{}return Qe.production}const Gs=2e3,rr=6e4,qs=1e3,Js=1e4,Vs="0x77359400",sr="0x3B9ACA00",nr=130,or=6,ir=18,zs=5*60*1e3,Ys=30*1e3,ae=class ae extends Hs{constructor(e,r,t,n,o,i,a,c,l,d,h){var w;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&Yt(e.logger),this.confirmation=l,this.pinStore=h??new tr,this.chainRegistry=d,this.jsonRpc=new Us(d,o),this.signInUseCase=new $s(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ws(this.internalConfig,t,c),this.migrateWalletUseCase=new Bs(t,a),(w=a.setOnUnauthorized)==null||w.call(a,()=>this.forceLogout())}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;u.log("[CROSSx SDK] v1.2.5 초기화 중..."),this.confirmation.setMessages(Zt(this._config.locale));try{const n=Ks();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const o=await this.signInUseCase.restoreSession();if(o!=null&&o.success){this.applyAuthResult(o);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(i){if(!(i instanceof x&&i.code===f.PIN_CANCELLED))throw i;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(o!=null&&o.success)}),o??null}catch(n){throw new x(f.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};r={...e,provider:t}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(f.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const r=await this.signIn(e);if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:o}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...r,address:(a==null?void 0:a.address)??o,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof x&&t.code===f.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new x(f.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(f.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(f.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof x&&r.code===f.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof x?r:new x(f.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.walletProvider.getAddresses(this.userId);return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.walletProvider.getAddresses(this.userId);r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.ensurePinForSigning();const n=r.length,i={address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,n))).address,index:n};return r.push(i),i},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(f.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof x?r:new x(f.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Zt(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const r=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",r);const t=await this.handleMigrationFlow(r);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new x(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const r=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof x&&r.code===f.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 x(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}await this.ensurePinSetup();try{const r=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof x&&r.code===f.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 x(f.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}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,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(f.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(r,i.signature,n.address),{chainId:e,signature:i.signature,message:r,address:n.address}}catch(i){throw i instanceof x?i:new x(f.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(f.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");ae.validateTypedDataChainId(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(f.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return ae.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(f.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,r){return this.signTypedData(ae.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=gt(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(f.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return ae.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(f.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(f.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const o=gt(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(f.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(f.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??qs,o=Js,i=t.timeoutMs??rr,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new x(f.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var v,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,r,i),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??Gs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??rr,d=gt(e),h=r.from??"";let w,p;const m=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{w=E;const k=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),B=r.value?BigInt(r.value):0n,b=ae.formatTxAmount(r.value,d.symbol,d.decimals),P=ae.formatTxAmount("0x"+k.toString(16),d.symbol,d.decimals),C=ae.formatTxAmount("0x"+(B+k).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:E.from,to:E.to??r.to,amount:b,fees:P,total:C,nativeSymbol:d.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(p=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:h,to:r.to,amount:ae.formatTxAmount(r.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:r.to},m),p)throw p;return{chainId:e,txHash:a,receipt:w}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new x(f.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof x?n:new x(f.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new x(f.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const o=n instanceof Error?n.message:String(n);throw new x(f.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${o}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new x(f.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new x(f.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(f.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:ae.formatWei(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(f.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const r=BigInt(e);if(r===0n)return"0";const t=10n**BigInt(ir),n=r/t,i=(r%t).toString().padStart(ir,"0").replace(/0+$/,"").slice(0,or);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new zt(this,e)}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(f.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${o}`,n)}}static formatTxAmount(e,r,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const o=10n**BigInt(t),i=n/o,c=(n%o).toString().padStart(t,"0").slice(0,or).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${r}`}catch{return}}async handleMigrationFlow(e){var a,c;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=await this.confirmation.showMigrationFoundPrompt();if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",r),r==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0,o=5,i=null;for(;;){n++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:t,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(l===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyRecoveryPin)==null?void 0:c.call(a,l,e));if(!d){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const h=d.pinStatus;if(o=h.maxAttempts,n=o-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const w=h.lockExpiresAt*1e3,p=Math.max(1,Math.round((w-Date.now())/1e3)),m=p<=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 잠금 — ${p}초, 메시지: ${m}`),await this.confirmation.showRecoveryPinLockedPrompt(p,m),n=0,t="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),t="Incorrect PIN."}catch(d){if(!(d instanceof x))throw d;if(d.code===f.MIGRATION_PIN_LOCKED){const h=d.details;if(o=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((h==null?void 0:h.lockExpiresAt)??0)*1e3,p=Math.max(1,Math.round((w-Date.now())/1e3)),m=p<=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 이미 잠금 — ${p}초`),await this.confirmation.showRecoveryPinLockedPrompt(p,m),n=0,t="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",d),d}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const l=await this.migrateWalletUseCase.execute(i,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof x&&l.code===f.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,r){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],r);c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,r),u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(r);if(l){const d=sr;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Vs,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=sr,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,r){const t=ae.extractDomainChainId(r);if(e==="0"){if(t!==void 0&&t!==0)throw new x(f.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new x(f.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new x(f.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${o})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const r=e.domain;if(r==null||typeof r!="object")return;const t=r.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new x(f.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(r.length!==nr)throw new x(f.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${nr} hex 문자(65 바이트) 예상, 현재 ${r.length}`)}static validateSignedTxFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new x(f.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(r.length<2)throw new x(f.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(f.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var r,t,n,o;this.authenticated=e.success,this.userId=((r=e.user)==null?void 0:r.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=ae.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new x(f.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 r=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new x(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(r),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r});if(!i)throw new x(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}const o=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof x){if(c.code===f.PIN_WRONG)return{ok:!1,error:"Incorrect PIN. Please try again."};if(c.code===f.PIN_INVALID)return{ok:!1,error:c.message};if(c.code===f.PIN_LOCKED)return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:(a=c.details)==null?void 0:a.lockExpiresAt}}throw c}}});if(!o)throw new x(f.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(o),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),t()}catch(o){throw n(o),o}finally{this._verifyPinMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const r=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",r),r!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let r,t;try{return await e()}catch(n){if(n instanceof x)if(n.code===f.PIN_WRONG)r="Incorrect PIN. Please enter your current PIN.";else if(n.code===f.PIN_INVALID)r=n.message;else if(n.code===f.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,r="Too many failed attempts. Your account is temporarily locked."}else throw n;else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",r),this.pinStore.clear(),await this.ensureVerifiedPin(r,t),t=void 0;try{return await e()}catch(n){if(n instanceof x){if(n.code===f.PIN_WRONG){r="Incorrect PIN. Please try again.";continue}if(n.code===f.PIN_INVALID){r=n.message;continue}if(n.code===f.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,r="Too many failed attempts. Your account is temporarily locked.";continue}}throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new x(f.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new x(f.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(f.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Yt(null)}};ae.OFFCHAIN_CHAIN_ID="0";let et=ae;class js{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return u.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw u.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw u.error("Storage clear error:",e),e}}}const xt="crossx-sdk",Zs=1,pe="data",Ne="keys",tt="aes-primary",Xs=12;class ar{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,Zs);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(pe)||o.createObjectStore(pe),o.objectStoreNames.contains(Ne)||o.createObjectStore(Ne)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(r);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,r,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(r);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((r,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>r(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,tt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,tt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===xt)return null;try{const e=await this.openDB(xt),r=e.transaction([Ne,pe],"readonly"),t=r.objectStore(Ne).get(tt),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const o=r.objectStore(pe).getAll(),i=r.objectStore(pe).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)}),new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)})]);e.close(),await this.idbPut(Ne,tt,n);for(let l=0;l<c.length;l++)await this.idbPut(pe,String(c[l]),a[l]);return indexedDB.deleteDatabase(xt),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(Xs);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(pe,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(pe,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return u.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(pe,e)}catch(r){throw u.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(pe)}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 mt=crypto,cr=s=>s instanceof CryptoKey,rt=new TextEncoder,Ge=new TextDecoder;function Qs(...s){const e=s.reduce((n,{length:o})=>n+o,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const en=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Ie=s=>{let e=s;e instanceof Uint8Array&&(e=Ge.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return en(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class X extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}X.code="ERR_JOSE_GENERIC";class he extends X{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class wt extends X{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}wt.code="ERR_JWT_EXPIRED";class lr extends X{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}lr.code="ERR_JOSE_ALG_NOT_ALLOWED";class _e extends X{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}_e.code="ERR_JOSE_NOT_SUPPORTED";class tn extends X{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}tn.code="ERR_JWE_DECRYPTION_FAILED";class rn extends X{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}rn.code="ERR_JWE_INVALID";class j extends X{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}j.code="ERR_JWS_INVALID";class ge extends X{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}ge.code="ERR_JWT_INVALID";class sn extends X{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}sn.code="ERR_JWK_INVALID";class yt extends X{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}yt.code="ERR_JWKS_INVALID";class bt extends X{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}bt.code="ERR_JWKS_NO_MATCHING_KEY";class dr extends X{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}dr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class ur extends X{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}ur.code="ERR_JWKS_TIMEOUT";class hr extends X{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}hr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function xe(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function qe(s,e){return s.name===e}function St(s){return parseInt(s.name.slice(4),10)}function nn(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function on(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function an(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!qe(s.algorithm,"HMAC"))throw xe("HMAC");const t=parseInt(e.slice(2),10);if(St(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!qe(s.algorithm,"RSASSA-PKCS1-v1_5"))throw xe("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(St(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!qe(s.algorithm,"RSA-PSS"))throw xe("RSA-PSS");const t=parseInt(e.slice(2),10);if(St(s.algorithm.hash)!==t)throw xe(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw xe("Ed25519 or Ed448");break}case"Ed25519":{if(!qe(s.algorithm,"Ed25519"))throw xe("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!qe(s.algorithm,"ECDSA"))throw xe("ECDSA");const t=nn(e);if(s.algorithm.namedCurve!==t)throw xe(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}on(s,r)}function fr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const pr=(s,...e)=>fr("Key must be ",s,...e);function _r(s,e,...r){return fr(`Key for the ${s} algorithm must be `,e,...r)}const gr=s=>cr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",st=["CryptoKey"],cn=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const o of n){if(r.has(o))return!1;r.add(o)}}return!0};function ln(s){return typeof s=="object"&&s!==null}function ye(s){if(!ln(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const dn=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function De(s){return ye(s)&&typeof s.kty=="string"}function un(s){return s.kty!=="oct"&&typeof s.d=="string"}function hn(s){return s.kty!=="oct"&&typeof s.d>"u"}function fn(s){return De(s)&&s.kty==="oct"&&typeof s.k=="string"}function pn(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new _e('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new _e('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const xr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=pn(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,mt.subtle.importKey("jwk",n,...t)},mr=s=>Ie(s);let Me,$e;const wr=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",nt=async(s,e,r,t,n=!1)=>{let o=s.get(e);if(o!=null&&o[t])return o[t];const i=await xr({...r,alg:t});return n&&Object.freeze(e),o?o[t]=i:s.set(e,{[t]:i}),i},_n={normalizePublicKey:(s,e)=>{if(wr(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?mr(r.k):($e||($e=new WeakMap),nt($e,s,r,e))}return De(s)?s.k?Ie(s.k):($e||($e=new WeakMap),nt($e,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(wr(s)){let r=s.export({format:"jwk"});return r.k?mr(r.k):(Me||(Me=new WeakMap),nt(Me,s,r,e))}return De(s)?s.k?Ie(s.k):(Me||(Me=new WeakMap),nt(Me,s,s,e,!0)):s}};async function yr(s,e){if(!ye(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Ie(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new _e('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return xr({...s,alg:e});default:throw new _e('Unsupported "kty" (Key Type) Parameter value')}}const We=s=>s==null?void 0:s[Symbol.toStringTag],vt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},gn=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&De(e)){if(fn(e)&&vt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!gr(e))throw new TypeError(_r(s,e,...st,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${We(e)} instances for symmetric algorithms must be of type "secret"`)}},xn=(s,e,r,t)=>{if(t&&De(e))switch(r){case"sign":if(un(e)&&vt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(hn(e)&&vt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!gr(e))throw new TypeError(_r(s,e,...st,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${We(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${We(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${We(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${We(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${We(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function br(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?gn(e,r,t,s):xn(e,r,t,s)}br.bind(void 0,!1);const Sr=br.bind(void 0,!0);function mn(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(i=>typeof i!="string"||i.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...e.entries()]):o=e;for(const i of t.crit){if(!o.has(i))throw new _e(`Extension Header Parameter "${i}" is not recognized`);if(n[i]===void 0)throw new s(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&t[i]===void 0)throw new s(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(t.crit)}const wn=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function yn(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new _e(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function bn(s,e,r){if(e=await _n.normalizePublicKey(e,s),cr(e))return an(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(pr(e,...st));return mt.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(pr(e,...st,"Uint8Array","JSON Web Key"))}const Sn=async(s,e,r,t)=>{const n=await bn(s,e,"verify");dn(s,n);const o=yn(s,n.algorithm);try{return await mt.subtle.verify(o,n,r,t)}catch{return!1}};async function vn(s,e,r){if(!ye(s))throw new j("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new j('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new j("JWS Protected Header incorrect type");if(s.payload===void 0)throw new j("JWS Payload missing");if(typeof s.signature!="string")throw new j("JWS Signature missing or incorrect type");if(s.header!==void 0&&!ye(s.header))throw new j("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const v=Ie(s.protected);t=JSON.parse(Ge.decode(v))}catch{throw new j("JWS Protected Header is invalid")}if(!cn(t,s.header))throw new j("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},o=mn(j,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let i=!0;if(o.has("b64")&&(i=t.b64,typeof i!="boolean"))throw new j('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new j('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&wn("algorithms",r.algorithms);if(c&&!c.has(a))throw new lr('"alg" (Algorithm) Header Parameter value not allowed');if(i){if(typeof s.payload!="string")throw new j("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new j("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Sr(a,e,"verify"),De(e)&&(e=await yr(e,a))):Sr(a,e,"verify");const d=Qs(rt.encode(s.protected??""),rt.encode("."),typeof s.payload=="string"?rt.encode(s.payload):s.payload);let h;try{h=Ie(s.signature)}catch{throw new j("Failed to base64url decode the signature")}if(!await Sn(a,e,h,d))throw new hr;let p;if(i)try{p=Ie(s.payload)}catch{throw new j("Failed to base64url decode the payload")}else typeof s.payload=="string"?p=rt.encode(s.payload):p=s.payload;const m={payload:p};return s.protected!==void 0&&(m.protectedHeader=t),s.header!==void 0&&(m.unprotectedHeader=s.header),l?{...m,key:e}:m}async function En(s,e,r){if(s instanceof Uint8Array&&(s=Ge.decode(s)),typeof s!="string")throw new j("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:o,length:i}=s.split(".");if(i!==3)throw new j("Invalid Compact JWS");const a=await vn({payload:n,protected:t,signature:o},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const In=s=>Math.floor(s.getTime()/1e3),vr=60,Er=vr*60,Et=Er*24,An=Et*7,Tn=Et*365.25,Rn=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Ir=s=>{const e=Rn.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*vr);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Er);break;case"day":case"days":case"d":n=Math.round(r*Et);break;case"week":case"weeks":case"w":n=Math.round(r*An);break;default:n=Math.round(r*Tn);break}return e[1]==="-"||e[4]==="ago"?-n:n},Ar=s=>s.toLowerCase().replace(/^application\//,""),Pn=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Cn=(s,e,r={})=>{let t;try{t=JSON.parse(Ge.decode(e))}catch{}if(!ye(t))throw new ge("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||Ar(s.typ)!==Ar(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:o=[],issuer:i,subject:a,audience:c,maxTokenAge:l}=r,d=[...o];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),i!==void 0&&d.push("iss");for(const m of new Set(d.reverse()))if(!(m in t))throw new he(`missing required "${m}" claim`,t,m,"missing");if(i&&!(Array.isArray(i)?i:[i]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Pn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let h;switch(typeof r.clockTolerance){case"string":h=Ir(r.clockTolerance);break;case"number":h=r.clockTolerance;break;case"undefined":h=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:w}=r,p=In(w||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>p+h)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=p-h)throw new wt('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const m=p-t.iat,v=typeof l=="number"?l:Ir(l);if(m-h>v)throw new wt('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(m<0-h)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function On(s,e,r){var i;const t=await En(s,e,r);if((i=t.protectedHeader.crit)!=null&&i.includes("b64")&&t.protectedHeader.b64===!1)throw new ge("JWTs MUST NOT use unencoded payload");const o={payload:Cn(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...o,key:t.key}:o}function Nn(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new _e('Unsupported "alg" value for a JSON Web Key Set')}}function kn(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Ln)}function Ln(s){return ye(s)}function Tr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Dn{constructor(e){if(this._cached=new WeakMap,!kn(e))throw new yt("JSON Web Key Set malformed");this._jwks=Tr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},o=Nn(t),i=this._jwks.keys.filter(l=>{let d=o===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}=i;if(c===0)throw new bt;if(c!==1){const l=new dr,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const h of i)try{yield await Rr(d,h,t)}catch{}},l}return Rr(this._cached,a,t)}}async function Rr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await yr({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new yt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function Pr(s){const e=new Dn(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Tr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Mn=async(s,e,r)=>{let t,n,o=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{o=!0,t.abort()},e));const i=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw o?new ur:a});if(n!==void 0&&clearTimeout(n),i.status!==200)throw new X("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await i.json()}catch{throw new X("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function $n(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let It;(typeof navigator>"u"||!((Ps=(_t=navigator.userAgent)==null?void 0:_t.startsWith)!=null&&Ps.call(_t,"Mozilla/5.0 ")))&&(It="jose/v5.10.0");const At=Symbol();function Wn(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!ye(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,ye))}class Bn{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[At])!==void 0&&(this._cache=r==null?void 0:r[At],Wn(r==null?void 0:r[At],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Pr(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof bt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&$n()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);It&&!e.has("User-Agent")&&(e.set("User-Agent",It),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Mn(this._url,this._timeoutDuration,this._options).then(r=>{this._local=Pr(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Un(s,e){const r=new Bn(s,e),t=async(n,o)=>r.getKey(n,o);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Hn=Ie;function Fn(s){if(typeof s!="string")throw new ge("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new ge("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new ge("Invalid JWT");if(!e)throw new ge("JWTs must contain a payload");let t;try{t=Hn(e)}catch{throw new ge("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Ge.decode(t))}catch{throw new ge("Failed to parse the decoded payload as JSON")}if(!ye(n))throw new ge("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Tt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function be(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function J(s,e,r=""){const t=Tt(s),n=s==null?void 0:s.length,o=e!==void 0;if(!t||o&&n!==e){const i=r&&`"${r}" `,a=o?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(i+"expected Uint8Array"+a+", got "+c)}return s}function Cr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");be(s.outputLen),be(s.blockLen)}function Be(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function Or(s,e){J(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Kn(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Ue(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Rt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function me(s,e){return s<<32-e|s>>>e}const Gn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function qn(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Jn(s){for(let e=0;e<s.length;e++)s[e]=qn(s[e]);return s}const Nr=Gn?s=>s:Jn,kr=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Vn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Je(s){if(J(s),kr)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Vn[s[r]];return e}const Se={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lr(s){if(s>=Se._0&&s<=Se._9)return s-Se._0;if(s>=Se.A&&s<=Se.F)return s-(Se.A-10);if(s>=Se.a&&s<=Se.f)return s-(Se.a-10)}function ot(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(kr)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,o=0;n<r;n++,o+=2){const i=Lr(s.charCodeAt(o)),a=Lr(s.charCodeAt(o+1));if(i===void 0||a===void 0){const c=s[o]+s[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function Ae(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];J(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const o=s[t];r.set(o,n),n+=o.length}return r}function Dr(s,e={}){const r=(n,o)=>s(o).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Mr(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const zn=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function Yn(s,e,r){return s&e^~s&r}function jn(s,e,r){return s&e^s&r^e&r}class Zn{constructor(e,r,t,n){A(this,"blockLen");A(this,"outputLen");A(this,"padOffset");A(this,"isLE");A(this,"buffer");A(this,"view");A(this,"finished",!1);A(this,"length",0);A(this,"pos",0);A(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Rt(this.buffer)}update(e){Be(this),J(e);const{view:r,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=Rt(e);for(;n<=o-i;i+=n)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Be(this),Or(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;r[i++]=128,Ue(this.buffer.subarray(i)),this.padOffset>n-i&&(this.process(t,0),i=0);for(let h=i;h<n;h++)r[h]=0;t.setBigUint64(n-8,BigInt(this.length*8),o),this.process(t,0);const a=Rt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],o)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Te=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),it=BigInt(2**32-1),$r=BigInt(32);function Xn(s,e=!1){return e?{h:Number(s&it),l:Number(s>>$r&it)}:{h:Number(s>>$r&it)|0,l:Number(s&it)|0}}function Qn(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let o=0;o<r;o++){const{h:i,l:a}=Xn(s[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const eo=(s,e,r)=>s<<r|e>>>32-r,to=(s,e,r)=>e<<r|s>>>32-r,ro=(s,e,r)=>e<<r-32|s>>>64-r,so=(s,e,r)=>s<<r-32|e>>>64-r,no=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]),Re=new Uint32Array(64);class oo extends Zn{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:o,F:i,G:a,H:c}=this;return[e,r,t,n,o,i,a,c]}set(e,r,t,n,o,i,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=o|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Re[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const w=Re[h-15],p=Re[h-2],m=me(w,7)^me(w,18)^w>>>3,v=me(p,17)^me(p,19)^p>>>10;Re[h]=v+Re[h-7]+m+Re[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){const w=me(a,6)^me(a,11)^me(a,25),p=d+w+Yn(a,c,l)+no[h]+Re[h]|0,v=(me(t,2)^me(t,13)^me(t,22))+jn(t,n,o)|0;d=l,l=c,c=a,a=i+p|0,i=o,o=n,n=t,t=p+v|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){Ue(Re)}destroy(){this.set(0,0,0,0,0,0,0,0),Ue(this.buffer)}}class io extends oo{constructor(){super(32);A(this,"A",Te[0]|0);A(this,"B",Te[1]|0);A(this,"C",Te[2]|0);A(this,"D",Te[3]|0);A(this,"E",Te[4]|0);A(this,"F",Te[5]|0);A(this,"G",Te[6]|0);A(this,"H",Te[7]|0)}}const ao=Dr(()=>new io,zn(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pt=BigInt(0),Ct=BigInt(1);function at(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Wr(s){if(typeof s=="bigint"){if(!dt(s))throw new Error("positive bigint expected, got "+s)}else be(s);return s}function ct(s){const e=Wr(s).toString(16);return e.length&1?"0"+e:e}function Br(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Pt:BigInt("0x"+s)}function lt(s){return Br(Je(s))}function Ur(s){return Br(Je(co(J(s)).reverse()))}function Ot(s,e){be(e),s=Wr(s);const r=ot(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Hr(s,e){return Ot(s,e).reverse()}function co(s){return Uint8Array.from(s)}const dt=s=>typeof s=="bigint"&&Pt<=s;function lo(s,e,r){return dt(s)&&dt(e)&&dt(r)&&e<=s&&s<r}function uo(s,e,r,t){if(!lo(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function ho(s){let e;for(e=0;s>Pt;s>>=Ct,e+=1);return e}const Nt=s=>(Ct<<BigInt(s))-Ct;function fo(s,e,r){if(be(s,"hashLen"),be(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),d=0;const h=()=>{c.fill(1),l.fill(0),d=0},w=(...y)=>r(l,Ae(c,...y)),p=(y=n)=>{l=w(o,y),c=w(),y.length!==0&&(l=w(i,y),c=w())},m=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const E=[];for(;y<e;){c=w();const k=c.slice();E.push(k),y+=c.length}return Ae(...E)};return(y,E)=>{h(),p(y);let k;for(;!(k=E(m()));)p();return h(),k}}function kt(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(o,i,a){const c=s[o];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${o}" is invalid: expected ${i}, got ${l}`)}const n=(o,i)=>Object.entries(o).forEach(([a,c])=>t(a,c,i));n(e,!1),n(r,!0)}function Fr(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const o=s(r,...t);return e.set(r,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ie=BigInt(0),ee=BigInt(1),ke=BigInt(2),Kr=BigInt(3),Gr=BigInt(4),qr=BigInt(5),po=BigInt(7),Jr=BigInt(8),_o=BigInt(9),Vr=BigInt(16);function fe(s,e){const r=s%e;return r>=ie?r:e+r}function de(s,e,r){let t=s;for(;e-- >ie;)t*=t,t%=r;return t}function zr(s,e){if(s===ie)throw new Error("invert: expected non-zero number");if(e<=ie)throw new Error("invert: expected positive modulus, got "+e);let r=fe(s,e),t=e,n=ie,o=ee;for(;r!==ie;){const a=t/r,c=t%r,l=n-o*a;t=r,r=c,n=o,o=l}if(t!==ee)throw new Error("invert: does not exist");return fe(n,e)}function Lt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function Yr(s,e){const r=(s.ORDER+ee)/Gr,t=s.pow(e,r);return Lt(s,t,e),t}function go(s,e){const r=(s.ORDER-qr)/Jr,t=s.mul(e,ke),n=s.pow(t,r),o=s.mul(e,n),i=s.mul(s.mul(o,ke),n),a=s.mul(o,s.sub(i,s.ONE));return Lt(s,a,e),a}function xo(s){const e=ut(s),r=jr(s),t=r(e,e.neg(e.ONE)),n=r(e,t),o=r(e,e.neg(t)),i=(s+po)/Vr;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const h=a.mul(l,n),w=a.mul(l,o),p=a.eql(a.sqr(d),c),m=a.eql(a.sqr(h),c);l=a.cmov(l,d,p),d=a.cmov(w,h,m);const v=a.eql(a.sqr(d),c),y=a.cmov(l,d,v);return Lt(a,y,c),y}}function jr(s){if(s<Kr)throw new Error("sqrt is not defined for small field");let e=s-ee,r=0;for(;e%ke===ie;)e/=ke,r++;let t=ke;const n=ut(s);for(;Xr(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Yr;let o=n.pow(t,e);const i=(e+ee)/ke;return function(c,l){if(c.is0(l))return l;if(Xr(c,l)!==1)throw new Error("Cannot find square root");let d=r,h=c.mul(c.ONE,o),w=c.pow(l,e),p=c.pow(l,i);for(;!c.eql(w,c.ONE);){if(c.is0(w))return c.ZERO;let m=1,v=c.sqr(w);for(;!c.eql(v,c.ONE);)if(m++,v=c.sqr(v),m===d)throw new Error("Cannot find square root");const y=ee<<BigInt(d-m-1),E=c.pow(h,y);d=m,h=c.sqr(E),w=c.mul(w,h),p=c.mul(p,E)}return p}}function mo(s){return s%Gr===Kr?Yr:s%Jr===qr?go:s%Vr===_o?xo(s):jr(s)}const wo=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function yo(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=wo.reduce((t,n)=>(t[n]="function",t),e);return kt(s,r),s}function bo(s,e,r){if(r<ie)throw new Error("invalid exponent, negatives unsupported");if(r===ie)return s.ONE;if(r===ee)return e;let t=s.ONE,n=e;for(;r>ie;)r&ee&&(t=s.mul(t,n)),n=s.sqr(n),r>>=ee;return t}function Zr(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((i,a,c)=>s.is0(a)?i:(t[c]=i,s.mul(i,a)),s.ONE),o=s.inv(n);return e.reduceRight((i,a,c)=>s.is0(a)?i:(t[c]=s.mul(i,t[c]),s.mul(i,a)),o),t}function Xr(s,e){const r=(s.ORDER-ee)/ke,t=s.pow(e,r),n=s.eql(t,s.ONE),o=s.eql(t,s.ZERO),i=s.eql(t,s.neg(s.ONE));if(!n&&!o&&!i)throw new Error("invalid Legendre symbol result");return n?1:o?0:-1}function So(s,e){e!==void 0&&be(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class vo{constructor(e,r={}){A(this,"ORDER");A(this,"BITS");A(this,"BYTES");A(this,"isLE");A(this,"ZERO",ie);A(this,"ONE",ee);A(this,"_lengths");A(this,"_sqrt");A(this,"_mod");var i;if(e<=ie)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(i=r.allowedLengths)==null?void 0:i.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:o}=So(e,t);if(o>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=o,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ie<=e&&e<this.ORDER}is0(e){return e===ie}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return fe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return fe(e*e,this.ORDER)}add(e,r){return fe(e+r,this.ORDER)}sub(e,r){return fe(e-r,this.ORDER)}mul(e,r){return fe(e*r,this.ORDER)}pow(e,r){return bo(this,e,r)}div(e,r){return fe(e*zr(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return zr(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=mo(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Hr(e,this.BYTES):Ot(e,this.BYTES)}fromBytes(e,r=!1){J(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?Ur(e):lt(e);if(a&&(c=fe(c,i)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return Zr(this,e)}cmov(e,r,t){return t?r:e}}function ut(s,e={}){return new vo(s,e)}function Qr(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function es(s){const e=Qr(s);return e+Math.ceil(e/2)}function Eo(s,e,r=!1){J(s);const t=s.length,n=Qr(e),o=es(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=r?Ur(s):lt(s),a=fe(i,e-ee)+ee;return r?Hr(a,n):Ot(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const He=BigInt(0),Le=BigInt(1);function ht(s,e){const r=e.negate();return s?r:e}function ts(s,e){const r=Zr(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function rs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Dt(s,e){rs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,o=Nt(s),i=BigInt(s);return{windows:r,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function ss(s,e,r){const{windowSize:t,mask:n,maxNumber:o,shiftBy:i}=r;let a=Number(s&n),c=s>>i;a>t&&(a-=o,c+=Le);const l=e*t,d=l+Math.abs(a)-1,h=a===0,w=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:w,isNegF:p,offsetF:l}}const Mt=new WeakMap,ns=new WeakMap;function $t(s){return ns.get(s)||1}function os(s){if(s!==He)throw new Error("invalid wNAF")}class Io{constructor(e,r){A(this,"BASE");A(this,"ZERO");A(this,"Fn");A(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>He;)r&Le&&(t=t.add(n)),n=n.double(),r>>=Le;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Dt(r,this.bits),o=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,o.push(a);for(let l=1;l<n;l++)a=a.add(i),o.push(a);i=a.double()}return o}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,o=this.BASE;const i=Dt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:w,offsetF:p}=ss(t,a,i);t=c,d?o=o.add(ht(w,r[p])):n=n.add(ht(h,r[l]))}return os(t),{p:n,f:o}}wNAFUnsafe(e,r,t,n=this.ZERO){const o=Dt(e,this.bits);for(let i=0;i<o.windows&&t!==He;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=ss(t,i,o);if(t=a,!l){const h=r[c];n=n.add(d?h.negate():h)}}return os(t),n}getPrecomputes(e,r,t){let n=Mt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Mt.set(r,n))),n}cached(e,r,t){const n=$t(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const o=$t(e);return o===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),r,n)}createCache(e,r){rs(r,this.bits),ns.set(e,r),Mt.delete(e)}hasCache(e){return $t(e)!==1}}function Ao(s,e,r,t){let n=e,o=s.ZERO,i=s.ZERO;for(;r>He||t>He;)r&Le&&(o=o.add(n)),t&Le&&(i=i.add(n)),n=n.double(),r>>=Le,t>>=Le;return{p1:o,p2:i}}function is(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return yo(e),e}else return ut(s,{isLE:r})}function To(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>He))throw new Error(`CURVE.${c} must be positive bigint`)}const n=is(e.p,r.Fp,t),o=is(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:o}}function Ro(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class as{constructor(e,r){A(this,"oHash");A(this,"iHash");A(this,"blockLen");A(this,"outputLen");A(this,"finished",!1);A(this,"destroyed",!1);if(Cr(e),J(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Ue(n)}update(e){return Be(this),this.iHash.update(e),this}digestInto(e){Be(this),J(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const cs=(s,e,r)=>new as(s,e).update(r).digest();cs.create=(s,e)=>new as(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ls=(s,e)=>(s+(s>=0?e:-e)/ds)/e;function Po(s,e,r){const[[t,n],[o,i]]=e,a=ls(i*s,r),c=ls(-n*s,r);let l=s-a*t-c*o,d=-a*n-c*i;const h=l<ve,w=d<ve;h&&(l=-l),w&&(d=-d);const p=Nt(Math.ceil(ho(r)/2))+Fe;if(l<ve||l>=p||d<ve||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:h,k1:l,k2neg:w,k2:d}}function Wt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Bt(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return at(r.lowS,"lowS"),at(r.prehash,"prehash"),r.format!==void 0&&Wt(r.format),r}class Co extends Error{constructor(e=""){super(e)}}const Pe={Err:Co,_tlv:{encode:(s,e)=>{const{Err:r}=Pe;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=ct(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const o=t>127?ct(n.length/2|128):"";return ct(s)+o+n+e},decode(s,e){const{Err:r}=Pe;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(s){const{Err:e}=Pe;if(s<ve)throw new e("integer: negative integers are not allowed");let r=ct(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=Pe;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return lt(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=Pe,n=J(s,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=Pe,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),o=t+n;return e.encode(48,o)}},ve=BigInt(0),Fe=BigInt(1),ds=BigInt(2),ft=BigInt(3),Oo=BigInt(4);function No(s,e={}){const r=To("weierstrass",s,e),{Fp:t,Fn:n}=r;let o=r.CURVE;const{h:i,n:a}=o;kt(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(o.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=hs(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(O,_,g){const{x:S,y:I}=_.toAffine(),L=t.toBytes(S);if(at(g,"isCompressed"),g){d();const N=!t.isOdd(I);return Ae(us(N),L)}else return Ae(Uint8Array.of(4),L,t.toBytes(I))}function w(O){J(O,void 0,"Point");const{publicKey:_,publicKeyUncompressed:g}=l,S=O.length,I=O[0],L=O.subarray(1);if(S===_&&(I===2||I===3)){const N=t.fromBytes(L);if(!t.isValid(N))throw new Error("bad point: is not on curve, wrong x");const M=v(N);let T;try{T=t.sqrt(M)}catch(Z){const q=Z instanceof Error?": "+Z.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}d();const $=t.isOdd(T);return(I&1)===1!==$&&(T=t.neg(T)),{x:N,y:T}}else if(S===g&&I===4){const N=t.BYTES,M=t.fromBytes(L.subarray(0,N)),T=t.fromBytes(L.subarray(N,N*2));if(!y(M,T))throw new Error("bad point: is not on curve");return{x:M,y:T}}else throw new Error(`bad point: got length ${S}, expected compressed=${_} or uncompressed=${g}`)}const p=e.toBytes||h,m=e.fromBytes||w;function v(O){const _=t.sqr(O),g=t.mul(_,O);return t.add(t.add(g,t.mul(O,o.a)),o.b)}function y(O,_){const g=t.sqr(_),S=v(O);return t.eql(g,S)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(o.a,ft),Oo),k=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(E,k)))throw new Error("bad curve params: a or b");function B(O,_,g=!1){if(!t.isValid(_)||g&&t.is0(_))throw new Error(`bad point coordinate ${O}`);return _}function b(O){if(!(O instanceof K))throw new Error("Weierstrass Point expected")}function P(O){if(!c||!c.basises)throw new Error("no endo");return Po(O,c.basises,n.ORDER)}const C=Fr((O,_)=>{const{X:g,Y:S,Z:I}=O;if(t.eql(I,t.ONE))return{x:g,y:S};const L=O.is0();_==null&&(_=L?t.ONE:t.inv(I));const N=t.mul(g,_),M=t.mul(S,_),T=t.mul(I,_);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:N,y:M}}),F=Fr(O=>{if(O.is0()){if(e.allowInfinityPoint&&!t.is0(O.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:g}=O.toAffine();if(!t.isValid(_)||!t.isValid(g))throw new Error("bad point: x or y not field elements");if(!y(_,g))throw new Error("bad point: equation left != right");if(!O.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function V(O,_,g,S,I){return g=new K(t.mul(g.X,O),g.Y,g.Z),_=ht(S,_),g=ht(I,g),_.add(g)}const R=class R{constructor(_,g,S){A(this,"X");A(this,"Y");A(this,"Z");this.X=B("x",_),this.Y=B("y",g,!0),this.Z=B("z",S),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){const{x:g,y:S}=_||{};if(!_||!t.isValid(g)||!t.isValid(S))throw new Error("invalid affine point");if(_ instanceof R)throw new Error("projective point not allowed");return t.is0(g)&&t.is0(S)?R.ZERO:new R(g,S,t.ONE)}static fromBytes(_){const g=R.fromAffine(m(J(_,void 0,"point")));return g.assertValidity(),g}static fromHex(_){return R.fromBytes(ot(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,g=!0){return D.createCache(this,_),g||this.multiply(ft),this}assertValidity(){F(this)}hasEvenY(){const{y:_}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(_)}equals(_){b(_);const{X:g,Y:S,Z:I}=this,{X:L,Y:N,Z:M}=_,T=t.eql(t.mul(g,M),t.mul(L,I)),$=t.eql(t.mul(S,M),t.mul(N,I));return T&&$}negate(){return new R(this.X,t.neg(this.Y),this.Z)}double(){const{a:_,b:g}=o,S=t.mul(g,ft),{X:I,Y:L,Z:N}=this;let M=t.ZERO,T=t.ZERO,$=t.ZERO,H=t.mul(I,I),Z=t.mul(L,L),q=t.mul(N,N),U=t.mul(I,L);return U=t.add(U,U),$=t.mul(I,N),$=t.add($,$),M=t.mul(_,$),T=t.mul(S,q),T=t.add(M,T),M=t.sub(Z,T),T=t.add(Z,T),T=t.mul(M,T),M=t.mul(U,M),$=t.mul(S,$),q=t.mul(_,q),U=t.sub(H,q),U=t.mul(_,U),U=t.add(U,$),$=t.add(H,H),H=t.add($,H),H=t.add(H,q),H=t.mul(H,U),T=t.add(T,H),q=t.mul(L,N),q=t.add(q,q),H=t.mul(q,U),M=t.sub(M,H),$=t.mul(q,Z),$=t.add($,$),$=t.add($,$),new R(M,T,$)}add(_){b(_);const{X:g,Y:S,Z:I}=this,{X:L,Y:N,Z:M}=_;let T=t.ZERO,$=t.ZERO,H=t.ZERO;const Z=o.a,q=t.mul(o.b,ft);let U=t.mul(g,L),Q=t.mul(S,N),se=t.mul(I,M),le=t.add(g,S),z=t.add(L,N);le=t.mul(le,z),z=t.add(U,Q),le=t.sub(le,z),z=t.add(g,I);let ne=t.add(L,M);return z=t.mul(z,ne),ne=t.add(U,se),z=t.sub(z,ne),ne=t.add(S,I),T=t.add(N,M),ne=t.mul(ne,T),T=t.add(Q,se),ne=t.sub(ne,T),H=t.mul(Z,z),T=t.mul(q,se),H=t.add(T,H),T=t.sub(Q,H),H=t.add(Q,H),$=t.mul(T,H),Q=t.add(U,U),Q=t.add(Q,U),se=t.mul(Z,se),z=t.mul(q,z),Q=t.add(Q,se),se=t.sub(U,se),se=t.mul(Z,se),z=t.add(z,se),U=t.mul(Q,z),$=t.add($,U),U=t.mul(ne,z),T=t.mul(le,T),T=t.sub(T,U),U=t.mul(le,Q),H=t.mul(ne,H),H=t.add(H,U),new R(T,$,H)}subtract(_){return this.add(_.negate())}is0(){return this.equals(R.ZERO)}multiply(_){const{endo:g}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let S,I;const L=N=>D.cached(this,N,M=>ts(R,M));if(g){const{k1neg:N,k1:M,k2neg:T,k2:$}=P(_),{p:H,f:Z}=L(M),{p:q,f:U}=L($);I=Z.add(U),S=V(g.beta,H,q,N,T)}else{const{p:N,f:M}=L(_);S=N,I=M}return ts(R,[S,I])[0]}multiplyUnsafe(_){const{endo:g}=e,S=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===ve||S.is0())return R.ZERO;if(_===Fe)return S;if(D.hasCache(this))return this.multiply(_);if(g){const{k1neg:I,k1:L,k2neg:N,k2:M}=P(_),{p1:T,p2:$}=Ao(R,S,L,M);return V(g.beta,T,$,I,N)}else return D.unsafe(S,_)}toAffine(_){return C(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return i===Fe?!0:_?_(R,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return i===Fe?this:_?_(R,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(_=!0){return at(_,"isCompressed"),this.assertValidity(),p(R,this,_)}toHex(_=!0){return Je(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};A(R,"BASE",new R(o.Gx,o.Gy,t.ONE)),A(R,"ZERO",new R(t.ZERO,t.ONE,t.ZERO)),A(R,"Fp",t),A(R,"Fn",n);let K=R;const G=n.BITS,D=new Io(K,e.endo?Math.ceil(G/2):G);return K.BASE.precompute(8),K}function us(s){return Uint8Array.of(s?2:3)}function hs(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ko(s,e={}){const{Fn:r}=s,t=e.randomBytes||Mr,n=Object.assign(hs(s.Fp,r),{seed:es(r.ORDER)});function o(p){try{const m=r.fromBytes(p);return r.isValidNot0(m)}catch{return!1}}function i(p,m){const{publicKey:v,publicKeyUncompressed:y}=n;try{const E=p.length;return m===!0&&E!==v||m===!1&&E!==y?!1:!!s.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Eo(J(p,n.seed,"seed"),r.ORDER)}function c(p,m=!0){return s.BASE.multiply(r.fromBytes(p)).toBytes(m)}function l(p){const{secretKey:m,publicKey:v,publicKeyUncompressed:y}=n;if(!Tt(p)||"_lengths"in r&&r._lengths||m===v)return;const E=J(p,void 0,"key").length;return E===v||E===y}function d(p,m,v=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(m)===!1)throw new Error("second arg must be public key");const y=r.fromBytes(p);return s.fromBytes(m).multiply(y).toBytes(v)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},w=Ro(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:w,Point:s,utils:h,lengths:n})}function Lo(s,e,r={}){Cr(e),kt(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Mr,n=r.hmac||((_,g)=>cs(e,_,g)),{Fp:o,Fn:i}=s,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:w,lengths:p}=ko(s,r),m={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},v=a*ds<o.ORDER;function y(_){const g=a>>Fe;return _>g}function E(_,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return g}function k(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(_,g){Wt(g);const S=p.signature,I=g==="compact"?S:g==="recovered"?S+1:void 0;return J(_,I)}class b{constructor(g,S,I){A(this,"r");A(this,"s");A(this,"recovery");if(this.r=E("r",g),this.s=E("s",S),I!=null){if(k(),![0,1,2,3].includes(I))throw new Error("invalid recovery id");this.recovery=I}Object.freeze(this)}static fromBytes(g,S=m.format){B(g,S);let I;if(S==="der"){const{r:T,s:$}=Pe.toSig(J(g));return new b(T,$)}S==="recovered"&&(I=g[0],S="compact",g=g.subarray(1));const L=p.signature/2,N=g.subarray(0,L),M=g.subarray(L,L*2);return new b(i.fromBytes(N),i.fromBytes(M),I)}static fromHex(g,S){return this.fromBytes(ot(g),S)}assertRecovery(){const{recovery:g}=this;if(g==null)throw new Error("invalid recovery id: must be present");return g}addRecoveryBit(g){return new b(this.r,this.s,g)}recoverPublicKey(g){const{r:S,s:I}=this,L=this.assertRecovery(),N=L===2||L===3?S+a:S;if(!o.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(N),T=s.fromBytes(Ae(us((L&1)===0),M)),$=i.inv(N),H=C(J(g,void 0,"msgHash")),Z=i.create(-H*$),q=i.create(I*$),U=s.BASE.multiplyUnsafe(Z).add(T.multiplyUnsafe(q));if(U.is0())throw new Error("invalid recovery: point at infinify");return U.assertValidity(),U}hasHighS(){return y(this.s)}toBytes(g=m.format){if(Wt(g),g==="der")return ot(Pe.hexFromSig(this));const{r:S,s:I}=this,L=i.toBytes(S),N=i.toBytes(I);return g==="recovered"?(k(),Ae(Uint8Array.of(this.assertRecovery()),L,N)):Ae(L,N)}toHex(g){return Je(this.toBytes(g))}}const P=r.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const S=lt(g),I=g.length*8-c;return I>0?S>>BigInt(I):S},C=r.bits2int_modN||function(g){return i.create(P(g))},F=Nt(c);function V(_){return uo("num < 2^"+c,_,ve,F),i.toBytes(_)}function K(_,g){return J(_,void 0,"message"),g?J(e(_),void 0,"prehashed message"):_}function G(_,g,S){const{lowS:I,prehash:L,extraEntropy:N}=Bt(S,m);_=K(_,L);const M=C(_),T=i.fromBytes(g);if(!i.isValidNot0(T))throw new Error("invalid private key");const $=[V(T),V(M)];if(N!=null&&N!==!1){const U=N===!0?t(p.secretKey):N;$.push(J(U,void 0,"extraEntropy"))}const H=Ae(...$),Z=M;function q(U){const Q=P(U);if(!i.isValidNot0(Q))return;const se=i.inv(Q),le=s.BASE.multiply(Q).toAffine(),z=i.create(le.x);if(z===ve)return;const ne=i.create(se*i.create(Z+z*T));if(ne===ve)return;let Cs=(le.x===z?0:2)|Number(le.y&Fe),Os=ne;return I&&y(ne)&&(Os=i.neg(ne),Cs^=1),new b(z,Os,v?void 0:Cs)}return{seed:H,k2sig:q}}function D(_,g,S={}){const{seed:I,k2sig:L}=G(_,g,S);return fo(e.outputLen,i.BYTES,n)(I,L).toBytes(S.format)}function R(_,g,S,I={}){const{lowS:L,prehash:N,format:M}=Bt(I,m);if(S=J(S,void 0,"publicKey"),g=K(g,N),!Tt(_)){const T=_ instanceof b?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}B(_,M);try{const T=b.fromBytes(_,M),$=s.fromBytes(S);if(L&&T.hasHighS())return!1;const{r:H,s:Z}=T,q=C(g),U=i.inv(Z),Q=i.create(q*U),se=i.create(H*U),le=s.BASE.multiplyUnsafe(Q).add($.multiplyUnsafe(se));return le.is0()?!1:i.create(le.x)===H}catch{return!1}}function O(_,g,S={}){const{prehash:I}=Bt(S,m);return g=K(g,I),b.fromBytes(_,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:w,lengths:p,Point:s,sign:D,verify:R,recoverPublicKey:O,Signature:b,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ut={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Do={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},fs=BigInt(2);function Mo(s){const e=Ut.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,d=l*l*s%e,h=de(d,r,e)*d%e,w=de(h,r,e)*d%e,p=de(w,fs,e)*l%e,m=de(p,n,e)*p%e,v=de(m,o,e)*m%e,y=de(v,a,e)*v%e,E=de(y,c,e)*y%e,k=de(E,a,e)*v%e,B=de(k,r,e)*d%e,b=de(B,i,e)*m%e,P=de(b,t,e)*l%e,C=de(P,fs,e);if(!Ht.eql(Ht.sqr(C),s))throw new Error("Cannot find square root");return C}const Ht=ut(Ut.p,{sqrt:Mo}),$o=Lo(No(Ut,{Fp:Ht,endo:Do}),ao),Wo=BigInt(0),Ve=BigInt(1),Bo=BigInt(2),Uo=BigInt(7),Ho=BigInt(256),Fo=BigInt(113),ps=[],_s=[],gs=[];for(let s=0,e=Ve,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],ps.push(2*(5*t+r)),_s.push((s+1)*(s+2)/2%64);let n=Wo;for(let o=0;o<7;o++)e=(e<<Ve^(e>>Uo)*Fo)%Ho,e&Bo&&(n^=Ve<<(Ve<<BigInt(o))-Ve);gs.push(n)}const xs=Qn(gs,!0),Ko=xs[0],Go=xs[1],ms=(s,e,r)=>r>32?ro(s,e,r):eo(s,e,r),ws=(s,e,r)=>r>32?so(s,e,r):to(s,e,r);function qo(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)r[i]=s[i]^s[i+10]^s[i+20]^s[i+30]^s[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=r[c],d=r[c+1],h=ms(l,d,1)^r[a],w=ws(l,d,1)^r[a+1];for(let p=0;p<50;p+=10)s[i+p]^=h,s[i+p+1]^=w}let n=s[2],o=s[3];for(let i=0;i<24;i++){const a=_s[i],c=ms(n,o,a),l=ws(n,o,a),d=ps[i];n=s[d],o=s[d+1],s[d]=c,s[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)r[a]=s[i+a];for(let a=0;a<10;a++)s[i+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=Ko[t],s[1]^=Go[t]}Ue(r)}class Ft{constructor(e,r,t,n=!1,o=24){A(this,"state");A(this,"pos",0);A(this,"posOut",0);A(this,"finished",!1);A(this,"state32");A(this,"destroyed",!1);A(this,"blockLen");A(this,"suffix");A(this,"outputLen");A(this,"enableXOF",!1);A(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=o,be(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Kn(this.state)}clone(){return this._cloneInto()}keccak(){Nr(this.state32),qo(this.state32,this.rounds),Nr(this.state32),this.posOut=0,this.pos=0}update(e){Be(this),J(e);const{blockLen:r,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(r-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Be(this,!1),J(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(r.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return be(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Or(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,Ue(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new Ft(r,t,n,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=t,e.outputLen=n,e.enableXOF=i,e.destroyed=this.destroyed,e}}const ys=((s,e,r,t={})=>Dr(()=>new Ft(e,s,r),t))(1,136,32),Jo=60;class Vo{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Un(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){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+Jo<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:o}=await On(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",o),{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 Fn(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
2
|
+
${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);const i=ys(o),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=zo(a),l=c.slice(0,32),d=c.slice(32,64),h=c[64],w=h>=27?h-27:h,v=new $o.Signature(bs(l),bs(d)).addRecoveryBit(w).recoverPublicKey(i).toBytes(!1).slice(1),y=ys(v);return"0x"+Je(y.slice(12))}}function zo(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function bs(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const Yo=3e4,jo=1e3;class Zo{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,jo*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??Yo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const Xo=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ce{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Ce.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n==="")throw u.error("[CROSSx] nonce claim 누락 — JWT payload 전체 키 목록:",Object.keys(t)),u.error("[CROSSx] 원인 추정: OAuth 서버가 Google/Apple 인증 요청에 nonce 파라미터를 포함하지 않았을 수 있습니다.","서버 로그에서 /auth/google, /auth/apple 요청 URL에 nonce 쿼리가 있는지 확인하세요."),new Error("ID Token에 nonce claim이 없습니다 — OAuth 서버 설정을 확인해 주세요");if(o.includes("appleid.apple.com")){const i=await Ce.sha256Hex(r);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Ce.generateRandom16Hex(),l=Ce.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const w=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!w){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),b(),t(new Error("Authentication timeout"))},5*60*1e3),m=10,v=30;let y=0,E=null;const k=()=>{clearInterval(B),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),E=setTimeout(()=>{b(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},B=setInterval(()=>{y++;try{w.closed&&(y<=m?k():(b(),t(new Error("로그인이 취소되었습니다"))))}catch{k()}},1e3),b=()=>{clearTimeout(p),clearInterval(B),E&&clearTimeout(E),window.removeEventListener("message",P)},P=C=>{var V,K,G,D,R;if(C.origin!==e.expectedOrigin)return;if(!Xo.has(C.origin)){u.error("[CROSSx] postMessage origin이 허용 목록에 없음:",C.origin),b(),t(new Error("Unauthorized OAuth origin"));return}b(),u.log("[CROSSx] OAuth postMessage 수신 — status:",C.data.status);const F=C.data.state??((V=C.data.data)==null?void 0:V.state);if(!F||F!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(C.data.status==="success"){const O=(K=C.data.data)==null?void 0:K.idToken,_=(G=C.data.data)==null?void 0:G.accessToken,g=_??O;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!_,hasIdToken:!!O}),!g){u.error("[CROSSx] 토큰을 찾을 수 없음:",C.data),t(new Error("Token not found in response"));return}O?Ce.verifyIdTokenNonce(O,l).then(()=>r(g)).catch(S=>{u.error("[CROSSx] nonce 검증 실패:",S),t(S instanceof Error?S:new Error("nonce verification failed"))}):_?_.split(".").length===3?Ce.verifyIdTokenNonce(_,l).then(()=>r(g)).catch(I=>{u.error("[CROSSx] accessToken nonce 검증 실패:",I),t(I instanceof Error?I:new Error("nonce verification failed"))}):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(g)):t(new Error("Token not found in response"))}else u.error("[CROSSx] OAuth 실패:",(D=C.data.data)==null?void 0:D.error),t(new Error(((R=C.data.data)==null?void 0:R.error)||"Authentication failed"))};window.addEventListener("message",P)})}}const ze="crossx_wallet_data",Ke="crossx_mock_pin_hash";class Qo{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(ze)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(ze);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(ze,n);const o=(r=this.pinStore)==null?void 0:r.get();return o&&(await this.storage.set(Ke,o),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(f.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(ze);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,o,i){return u.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,o,i){return u.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${o} from=${i}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,o){u.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,r,t,n){return u.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ke);return r&&r!==e?!1:(r||await this.storage.set(Ke,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var o;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(f.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Ke);if(n&&t&&n!==t)throw new x(f.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ke,r),u.log("[Mock] changePin 완료")}async migrateWallet(e,r){var o;if(u.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new x(f.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new x(f.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(ze,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Ke,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){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 Ye{constructor(e,r,t,n,o){this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=o??null}setOnUnauthorized(e){this._onUnauthorized=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new x(f.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,r,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${r}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const h=d.message||d.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:h,url:o,method:e});const w=Ye.mapGatewayError(d.code,d.data),p=Ye.getGatewayErrorMessage(d.code,h),m=d.data,v=w===f.PIN_LOCKED?Ye.extractLockDetails(m):m??void 0,y=new x(w,p,v);throw w===f.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(u.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof x)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,h=d.message||d.data||"API 요청에 실패했습니다",w=d.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:w,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new x(f.UNKNOWN_ERROR,`Wallet Gateway 오류 (${w}): ${h}`)}throw l}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new x(f.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new x(f.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new x(f.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new x(f.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,r,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,i);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,o)).txHash}}async migrateWallet(e,r){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e};return(await this.request("POST","/mnemonic/verify-password",r)).valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new x(f.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??e,t=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);return t?{lockExpiresAt:t>1e10?t:t*1e3}:{}}static mapGatewayError(e,r){switch(e){case-10002:return f.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return f.UNKNOWN_ERROR;case-10006:return f.GATEWAY_INTERNAL_ERROR;case-10008:return f.GATEWAY_LOCK_CONFLICT;case-10010:return f.MIGRATION_FAILED;case-10012:return f.MIGRATION_BACKUP_EXISTS;case-10027:return f.MIGRATION_PIN_LOCKED;case-10022:return f.PROJECT_NOT_REGISTERED;case-10023:return f.PROJECT_ID_MISSING;case-10024:return f.ORIGIN_NOT_ALLOWED;case-10028:return f.PIN_WRONG;case-10029:return f.PIN_INVALID;case-10031:return f.PIN_LOCKED;case-10030:return f.WALLET_INCONSISTENT_STATE;case-10026:return f.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return f.PREPARE_FAILED;case-10016:return f.PREPARE_EXPIRED;case-10017:case-10018:return f.PREPARE_MISMATCH;default:return f.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Invalid PIN format. Please enter a 6-digit numeric PIN.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";default:return`Request failed (${e}): ${r}`}}}class je{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=je.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?Ys:zs;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new x(je.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=je.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new x(f.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(Ze).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return f.CHAIN_NOT_SUPPORTED;case-10021:return f.INVALID_CHAIN;case-10022:return f.PROJECT_NOT_REGISTERED;case-10023:return f.PROJECT_ID_MISSING;case-10024:return f.APP_IDENTIFIER_MISSING;case-10025:return f.INVALID_APP_TYPE;default:return f.UNKNOWN_ERROR}}}const Ss="__crossx-confirm-style",te="__crossx-confirm-overlay",ei={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 vs(s,e){const r=ei[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const ti=`
|
|
3
3
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
4
4
|
|
|
5
|
-
#${
|
|
5
|
+
#${te} {
|
|
6
6
|
position: fixed;
|
|
7
7
|
inset: 0;
|
|
8
8
|
z-index: 2147483647;
|
|
@@ -1194,7 +1194,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1194
1194
|
|
|
1195
1195
|
/* ── Mobile bottom sheet ───────────────────────────────────── */
|
|
1196
1196
|
@media (max-width: 480px) {
|
|
1197
|
-
#${
|
|
1197
|
+
#${te} { align-items: flex-end; }
|
|
1198
1198
|
.__crossx-card {
|
|
1199
1199
|
width: 100%;
|
|
1200
1200
|
max-width: 100%;
|
|
@@ -1333,7 +1333,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1333
1333
|
|
|
1334
1334
|
/* ── Landscape for signing/transaction modals ──────────── */
|
|
1335
1335
|
@media (orientation: landscape) and (max-height: 500px) {
|
|
1336
|
-
#${
|
|
1336
|
+
#${te} { align-items: center !important; overflow: hidden; }
|
|
1337
1337
|
.__crossx-card--send-tx,
|
|
1338
1338
|
.__crossx-card--sign-tx,
|
|
1339
1339
|
.__crossx-card--sign-msg,
|
|
@@ -1650,57 +1650,57 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1650
1650
|
opacity: 0.5;
|
|
1651
1651
|
cursor: default;
|
|
1652
1652
|
}
|
|
1653
|
-
`;function
|
|
1653
|
+
`;function we(){let s=document.getElementById(Ss);s||(s=document.createElement("style"),s.id=Ss,document.head.appendChild(s)),s.textContent=ti}function re(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function ri(s,e="CROSS",r=18){if(!s||s==="0x"||s==="0x0")return null;try{const t=BigInt(s);if(t===0n)return null;const n=Kt(t,r);return n==="0"?null:`${n} ${e}`}catch{return null}}const Es={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 Is(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&Es[e]?Es[e]:s}function Kt(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,i=(s%r).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function Gt(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function si(s){try{return BigInt(s).toLocaleString()}catch{return s}}function ni(s){const{gasLimit:e,gasPrice:r,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=s;if(!e)return null;try{const a=BigInt(e),c=si(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${Kt(l,i)} ${o}`,maxFeeGwei:Gt(t),maxPriorityFeeGwei:n?Gt(n):void 0,gasLimitFormatted:c}}if(r){const l=a*BigInt(r);return{isDynamic:!1,estTxFee:`${Kt(l,i)} ${o}`,gasPriceGwei:Gt(r),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function As(s){const e=ni(s);if(!e)return Y("Estimated fee","<span>—</span>");let r=Y("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(r+=Y("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(r+=Y("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(r+=Y("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(r+=Y("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),r}const Ee=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1654
1654
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1655
1655
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1656
|
-
</svg>`,
|
|
1656
|
+
</svg>`,ce=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
1657
1657
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
1658
1658
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
1659
|
-
</svg>`,
|
|
1659
|
+
</svg>`,oi=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1660
1660
|
<circle cx="20" cy="20" r="20" fill="#00D5AA"/>
|
|
1661
1661
|
<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"/>
|
|
1662
|
-
</svg>`,
|
|
1662
|
+
</svg>`,qt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
|
|
1663
1663
|
<rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
|
|
1664
1664
|
<path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
|
|
1665
1665
|
<rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
|
|
1666
|
-
</svg>`,
|
|
1666
|
+
</svg>`,ii=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
1667
1667
|
<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)"/>
|
|
1668
|
-
</svg>`,
|
|
1668
|
+
</svg>`,ai=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none">
|
|
1669
1669
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
1670
1670
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
1671
1671
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
1672
|
-
</svg>`;function
|
|
1672
|
+
</svg>`;function ue(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function Y(s,e){return`
|
|
1673
1673
|
<div class="__crossx-row">
|
|
1674
|
-
<span class="__crossx-row-label">${
|
|
1674
|
+
<span class="__crossx-row-label">${s}</span>
|
|
1675
1675
|
<div class="__crossx-row-value">${e}</div>
|
|
1676
|
-
</div>`}function
|
|
1677
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1678
|
-
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${
|
|
1676
|
+
</div>`}function ci(s,e){const r=e,t=pt(s.dappName),n=s.to?`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1677
|
+
<button class="__crossx-copy-btn" data-copy="${W(s.to)}" title="Copy address">${Ee}</button>`:"<span>—</span>",o=As(s),i=s.data??"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
1678
|
+
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1679
1679
|
<div class="__crossx-header">
|
|
1680
1680
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
1681
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1681
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1682
1682
|
</div>
|
|
1683
1683
|
<hr class="__crossx-divider">
|
|
1684
1684
|
<div class="__crossx-body">
|
|
1685
1685
|
<div class="__crossx-body-cols">
|
|
1686
1686
|
<div class="__crossx-col-left">
|
|
1687
1687
|
<p class="__crossx-sig-subtitle">
|
|
1688
|
-
<span class="__crossx-sig-origin">${
|
|
1688
|
+
<span class="__crossx-sig-origin">${W(t)} </span>is requesting a Signature
|
|
1689
1689
|
</p>
|
|
1690
1690
|
<div class="__crossx-addr-pill">
|
|
1691
|
-
${
|
|
1692
|
-
<span class="__crossx-addr-pill-text">${
|
|
1691
|
+
${qt}
|
|
1692
|
+
<span class="__crossx-addr-pill-text">${re(s.from)}</span>
|
|
1693
1693
|
</div>
|
|
1694
1694
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1695
1695
|
</div>
|
|
1696
1696
|
<hr class="__crossx-divider __crossx-divider--cols">
|
|
1697
1697
|
<div class="__crossx-col-right-sign">
|
|
1698
1698
|
<div class="__crossx-rows">
|
|
1699
|
-
${
|
|
1700
|
-
${
|
|
1699
|
+
${Y("To",n)}
|
|
1700
|
+
${Y("Network",`<span>${Is(s.chainId)}</span>`)}
|
|
1701
1701
|
${o}
|
|
1702
1702
|
</div>
|
|
1703
|
-
<pre class="__crossx-raw-tx">${
|
|
1703
|
+
<pre class="__crossx-raw-tx">${W(i)}</pre>
|
|
1704
1704
|
</div>
|
|
1705
1705
|
</div>
|
|
1706
1706
|
<div class="__crossx-btn-row">
|
|
@@ -1709,48 +1709,48 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1709
1709
|
</div>
|
|
1710
1710
|
</div>
|
|
1711
1711
|
</div>
|
|
1712
|
-
`,a}function
|
|
1713
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1714
|
-
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${
|
|
1712
|
+
`,a}function li(s,e){const r=e,t=s.nativeSymbol??"ETH",n=s.nativeDecimals??18,o=pt(s.dappName),i=s.to?`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1713
|
+
<button class="__crossx-copy-btn" data-copy="${W(s.to)}" title="Copy address">${Ee}</button>`:"<span>—</span>",a=As(s),l=ri(s.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
|
|
1714
|
+
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1715
1715
|
<div class="__crossx-header">
|
|
1716
1716
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
1717
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1717
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1718
1718
|
</div>
|
|
1719
1719
|
<hr class="__crossx-divider">
|
|
1720
1720
|
<div class="__crossx-body">
|
|
1721
1721
|
<p class="__crossx-tx-subtitle">
|
|
1722
|
-
<span class="__crossx-sig-origin">${
|
|
1722
|
+
<span class="__crossx-sig-origin">${W(o)}</span> wants your permission to approve the following transaction.
|
|
1723
1723
|
</p>
|
|
1724
1724
|
<div class="__crossx-body-cols">
|
|
1725
1725
|
<div class="__crossx-rows">
|
|
1726
|
-
${
|
|
1727
|
-
${
|
|
1726
|
+
${Y("To",i)}
|
|
1727
|
+
${Y("Network",`<span>${Is(s.chainId)}</span>`)}
|
|
1728
1728
|
${a}
|
|
1729
1729
|
</div>
|
|
1730
1730
|
<div class="__crossx-pill">
|
|
1731
|
-
<span class="__crossx-pill-from">${
|
|
1731
|
+
<span class="__crossx-pill-from">${re(s.from)}</span>
|
|
1732
1732
|
<span class="__crossx-pill-amount">${l}</span>
|
|
1733
1733
|
</div>
|
|
1734
1734
|
</div>
|
|
1735
1735
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
1736
1736
|
</div>
|
|
1737
1737
|
</div>
|
|
1738
|
-
`,d}function
|
|
1739
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1740
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1741
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1738
|
+
`,d}function pt(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function W(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function di(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function ui(s){if(typeof s=="string")return W(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return W(JSON.stringify(s))}catch{return String(s)}}function hi(s,e){const r=Y("From",`<span class="__crossx-addr-text">${re(s.from)}</span>
|
|
1739
|
+
<button class="__crossx-copy-btn" data-copy="${W(s.from)}" title="Copy address">${Ee}</button>`),t=s.to?Y("To",`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1740
|
+
<button class="__crossx-copy-btn" data-copy="${W(s.to)}" title="Copy address">${Ee}</button>`):"",n=s.amount?Y("Transfer",`<span>${W(s.amount)}</span>`):"",o=s.fees?Y("Tx Fee",`<span>${W(s.fees)}</span>`):"",i=s.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${re(s.txHash)}</span>
|
|
1741
|
+
<button class="__crossx-copy-btn" data-copy="${W(s.txHash)}" title="Copy hash">${Ee}</button>`):"",a=s.total?`<div class="__crossx-total-pill">
|
|
1742
1742
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1743
|
-
<span class="__crossx-total-amount">${
|
|
1744
|
-
</div>`:"",c=document.createElement("div");return c.id=
|
|
1745
|
-
<div class="__crossx-card __crossx-card--migration" style="${
|
|
1743
|
+
<span class="__crossx-total-amount">${W(s.total)}</span>
|
|
1744
|
+
</div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
1745
|
+
<div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1746
1746
|
<div class="__crossx-header">
|
|
1747
1747
|
<p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
|
|
1748
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1748
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1749
1749
|
</div>
|
|
1750
1750
|
<hr class="__crossx-divider">
|
|
1751
1751
|
<div class="__crossx-body">
|
|
1752
1752
|
<div class="__crossx-rows">
|
|
1753
|
-
${
|
|
1753
|
+
${r}
|
|
1754
1754
|
${t}
|
|
1755
1755
|
${n}
|
|
1756
1756
|
${o}
|
|
@@ -1760,8 +1760,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1760
1760
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
1761
1761
|
</div>
|
|
1762
1762
|
</div>
|
|
1763
|
-
`,c}function
|
|
1764
|
-
<div class="__crossx-card __crossx-card--migration" style="${
|
|
1763
|
+
`,c}function fi(s,e){const r=document.createElement("div");return r.id=te,r.innerHTML=`
|
|
1764
|
+
<div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1765
1765
|
<div class="__crossx-header">
|
|
1766
1766
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
1767
1767
|
</div>
|
|
@@ -1773,38 +1773,38 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1773
1773
|
</div>
|
|
1774
1774
|
</div>
|
|
1775
1775
|
</div>
|
|
1776
|
-
`,
|
|
1777
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1778
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1779
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1776
|
+
`,r}function pi(s,e,r){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=s.querySelector("#__crossx-ttl"),i=s.querySelector(".__crossx-header");if(o){const m=n?ai:t?"":ii,v=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";m?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${m}<span>${v}</span>`):o.textContent=v}if(i&&!s.querySelector("#__crossx-close-btn")){const m=document.createElement("button");m.className="__crossx-close",m.id="__crossx-close-btn",m.setAttribute("aria-label","Close"),m.innerHTML=ce,i.appendChild(m)}const a=s.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?Y("From",`<span class="__crossx-addr-text">${re(e.from)}</span>
|
|
1777
|
+
<button class="__crossx-copy-btn" data-copy="${W(e.from)}" title="Copy address">${Ee}</button>`):"",l=e.to?Y("To",`<span class="__crossx-addr-text">${re(e.to)}</span>
|
|
1778
|
+
<button class="__crossx-copy-btn" data-copy="${W(e.to)}" title="Copy address">${Ee}</button>`):"",d=e.amount?Y("Transfer",`<span>${W(e.amount)}</span>`):"",h=e.fees?Y("Tx Fee",`<span>${W(e.fees)}</span>`):"",w=e.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${re(e.txHash)}</span>
|
|
1779
|
+
<button class="__crossx-copy-btn" data-copy="${W(e.txHash)}" title="Copy hash">${Ee}</button>`):"",p=e.total?`<div class="__crossx-total-pill">
|
|
1780
1780
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1781
|
-
<span class="__crossx-total-amount">${
|
|
1781
|
+
<span class="__crossx-total-amount">${W(e.total)}</span>
|
|
1782
1782
|
</div>`:"";a.innerHTML=`
|
|
1783
1783
|
<div class="__crossx-rows">
|
|
1784
1784
|
${c}
|
|
1785
1785
|
${l}
|
|
1786
1786
|
${d}
|
|
1787
1787
|
${h}
|
|
1788
|
-
${
|
|
1788
|
+
${w}
|
|
1789
1789
|
</div>
|
|
1790
|
-
${
|
|
1790
|
+
${p}
|
|
1791
1791
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1792
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(
|
|
1793
|
-
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${
|
|
1792
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(m=>{m.addEventListener("click",v=>{var E;v.stopPropagation();const y=m.dataset.copy;y&&((E=navigator.clipboard)==null||E.writeText(y).catch(()=>{}))})})}function _i(s,e){const r=e,t=pt(s.dappName),n=W(s.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
|
|
1793
|
+
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1794
1794
|
<div class="__crossx-header">
|
|
1795
1795
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
1796
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1796
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1797
1797
|
</div>
|
|
1798
1798
|
<hr class="__crossx-divider">
|
|
1799
1799
|
<div class="__crossx-body">
|
|
1800
1800
|
<div class="__crossx-body-cols">
|
|
1801
1801
|
<div class="__crossx-col-left">
|
|
1802
1802
|
<p class="__crossx-sig-subtitle">
|
|
1803
|
-
<span class="__crossx-sig-origin">${
|
|
1803
|
+
<span class="__crossx-sig-origin">${W(t)} </span>is requesting a Signature
|
|
1804
1804
|
</p>
|
|
1805
1805
|
<div class="__crossx-addr-pill">
|
|
1806
|
-
${
|
|
1807
|
-
<span class="__crossx-addr-pill-text">${
|
|
1806
|
+
${qt}
|
|
1807
|
+
<span class="__crossx-addr-pill-text">${re(s.from)}</span>
|
|
1808
1808
|
</div>
|
|
1809
1809
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1810
1810
|
</div>
|
|
@@ -1817,31 +1817,31 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1817
1817
|
</div>
|
|
1818
1818
|
</div>
|
|
1819
1819
|
</div>
|
|
1820
|
-
`,o}function
|
|
1820
|
+
`,o}function gi(s,e){const r=e,t=pt(s.dappName);let n={};if(typeof s.typedData=="string")try{n=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(n=s.typedData);const o=n.primaryType??"—",i=n.message??{};let a=`
|
|
1821
1821
|
<div class="__crossx-td-row">
|
|
1822
1822
|
<span class="__crossx-td-label">Primary Type</span>
|
|
1823
|
-
<span class="__crossx-td-value">${
|
|
1824
|
-
</div>`;for(const[l,d]of Object.entries(i)){const h=
|
|
1825
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1823
|
+
<span class="__crossx-td-value">${W(o)}</span>
|
|
1824
|
+
</div>`;for(const[l,d]of Object.entries(i)){const h=ui(d),p=di(d)?`<span class="__crossx-addr-text">${re(d)}</span>
|
|
1825
|
+
<button class="__crossx-copy-btn" data-copy="${W(String(d))}" title="Copy">${Ee}</button>`:`<span>${h}</span>`;a+=`
|
|
1826
1826
|
<div class="__crossx-td-row">
|
|
1827
|
-
<span class="__crossx-td-label">${
|
|
1828
|
-
<div class="__crossx-td-value">${
|
|
1829
|
-
</div>`}const c=document.createElement("div");return c.id=
|
|
1830
|
-
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${
|
|
1827
|
+
<span class="__crossx-td-label">${W(l)}</span>
|
|
1828
|
+
<div class="__crossx-td-value">${p}</div>
|
|
1829
|
+
</div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
1830
|
+
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1831
1831
|
<div class="__crossx-header">
|
|
1832
1832
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
1833
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1833
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1834
1834
|
</div>
|
|
1835
1835
|
<hr class="__crossx-divider">
|
|
1836
1836
|
<div class="__crossx-body">
|
|
1837
1837
|
<div class="__crossx-body-cols">
|
|
1838
1838
|
<div class="__crossx-col-left">
|
|
1839
1839
|
<p class="__crossx-sig-subtitle">
|
|
1840
|
-
<span class="__crossx-sig-origin">${
|
|
1840
|
+
<span class="__crossx-sig-origin">${W(t)} </span>is requesting a Signature
|
|
1841
1841
|
</p>
|
|
1842
1842
|
<div class="__crossx-addr-pill">
|
|
1843
|
-
${
|
|
1844
|
-
<span class="__crossx-addr-pill-text">${
|
|
1843
|
+
${qt}
|
|
1844
|
+
<span class="__crossx-addr-pill-text">${re(s.from)}</span>
|
|
1845
1845
|
</div>
|
|
1846
1846
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1847
1847
|
</div>
|
|
@@ -1854,19 +1854,19 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1854
1854
|
</div>
|
|
1855
1855
|
</div>
|
|
1856
1856
|
</div>
|
|
1857
|
-
`,c}const
|
|
1857
|
+
`,c}const xi=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1858
1858
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
1859
1859
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
1860
|
-
</svg>`;function
|
|
1861
|
-
<span class="__crossx-wallet-addr">${
|
|
1862
|
-
</button>`}).join(""),o=document.createElement("div");return o.id=
|
|
1863
|
-
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${
|
|
1860
|
+
</svg>`;function mi(s,e,r){const t=r==null?void 0:r.toLowerCase(),n=s.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${W(i.address)}">
|
|
1861
|
+
<span class="__crossx-wallet-addr">${re(i.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
1862
|
+
</button>`}).join(""),o=document.createElement("div");return o.id=te,o.innerHTML=`
|
|
1863
|
+
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1864
1864
|
<div class="__crossx-header">
|
|
1865
1865
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
1866
1866
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Select Connected Wallet</p>
|
|
1867
1867
|
<p class="__crossx-subtitle--body">Please select the wallet you previously used for this game to continue.</p>
|
|
1868
1868
|
</div>
|
|
1869
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1869
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1870
1870
|
</div>
|
|
1871
1871
|
<hr class="__crossx-divider">
|
|
1872
1872
|
<div class="__crossx-body">
|
|
@@ -1883,39 +1883,39 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1883
1883
|
${n}
|
|
1884
1884
|
</div>
|
|
1885
1885
|
<button class="__crossx-wallet-add" id="__crossx-add-wallet-btn" type="button">
|
|
1886
|
-
<span class="__crossx-wallet-add-icon">${
|
|
1886
|
+
<span class="__crossx-wallet-add-icon">${xi}</span>
|
|
1887
1887
|
<span class="__crossx-wallet-add-label">add a wallet</span>
|
|
1888
1888
|
</button>
|
|
1889
1889
|
</div>
|
|
1890
1890
|
</div>
|
|
1891
1891
|
</div>
|
|
1892
1892
|
</div>
|
|
1893
|
-
`,o}const
|
|
1893
|
+
`,o}const wi=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1894
1894
|
<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"/>
|
|
1895
1895
|
<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"/>
|
|
1896
|
-
</svg>`,
|
|
1896
|
+
</svg>`,yi=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1897
1897
|
<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"/>
|
|
1898
1898
|
<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"/>
|
|
1899
1899
|
<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"/>
|
|
1900
1900
|
<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"/>
|
|
1901
|
-
</svg>`;function
|
|
1902
|
-
<div class="__crossx-card __crossx-card--migration" style="${
|
|
1901
|
+
</svg>`;function bi(s){const e=s,r=document.createElement("div");return r.id=te,r.innerHTML=`
|
|
1902
|
+
<div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1903
1903
|
<div class="__crossx-header">
|
|
1904
1904
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
1905
1905
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Welcome onboard</p>
|
|
1906
1906
|
<p class="__crossx-subtitle">Creating CROSSx Embedded Wallet</p>
|
|
1907
1907
|
</div>
|
|
1908
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1908
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1909
1909
|
</div>
|
|
1910
1910
|
<hr class="__crossx-divider">
|
|
1911
1911
|
<div class="__crossx-body">
|
|
1912
1912
|
<div class="__crossx-login-btn-row">
|
|
1913
1913
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
1914
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
1914
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${wi}</span>
|
|
1915
1915
|
<span class="__crossx-login-btn-label">Sign in with Apple</span>
|
|
1916
1916
|
</button>
|
|
1917
1917
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
1918
|
-
<span class="__crossx-login-icon">${
|
|
1918
|
+
<span class="__crossx-login-icon">${yi}</span>
|
|
1919
1919
|
<span class="__crossx-login-btn-label">Sign in with Google</span>
|
|
1920
1920
|
</button>
|
|
1921
1921
|
</div>
|
|
@@ -1925,12 +1925,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1925
1925
|
</p>
|
|
1926
1926
|
</div>
|
|
1927
1927
|
</div>
|
|
1928
|
-
`,
|
|
1929
|
-
<div class="__crossx-card __crossx-card--migration" style="${
|
|
1928
|
+
`,r}function Si(s){const e=s,r=document.createElement("div");return r.id=te,r.innerHTML=`
|
|
1929
|
+
<div class="__crossx-card __crossx-card--migration" style="${ue(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1930
1930
|
<div class="__crossx-header">
|
|
1931
1931
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
1932
1932
|
<p class="__crossx-subtitle--body">We found a wallet linked to your social account. Enter your 4-digit PIN to restore your assets.</p>
|
|
1933
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1933
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1934
1934
|
</div>
|
|
1935
1935
|
<hr class="__crossx-divider">
|
|
1936
1936
|
<div class="__crossx-body">
|
|
@@ -1939,17 +1939,17 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1939
1939
|
<p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
|
|
1940
1940
|
</div>
|
|
1941
1941
|
<button class="__crossx-recover-btn" id="__crossx-recover-btn">
|
|
1942
|
-
<span class="__crossx-recover-icon">${
|
|
1942
|
+
<span class="__crossx-recover-icon">${oi}</span>
|
|
1943
1943
|
<span class="__crossx-recover-label">Import from Social Backup</span>
|
|
1944
1944
|
</button>
|
|
1945
1945
|
<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
|
|
1946
1946
|
</div>
|
|
1947
1947
|
</div>
|
|
1948
|
-
`,
|
|
1949
|
-
<div class="__crossx-card __crossx-card--migration" style="${
|
|
1948
|
+
`,r}function vi(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:o=5}=e??{},i=!!t,a=i?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${o}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",h=document.createElement("div");return h.id=te,h.innerHTML=`
|
|
1949
|
+
<div class="__crossx-card __crossx-card--migration" style="${ue(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1950
1950
|
<div class="__crossx-header">
|
|
1951
1951
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
1952
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1952
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1953
1953
|
</div>
|
|
1954
1954
|
<hr class="__crossx-divider">
|
|
1955
1955
|
<div class="__crossx-pin-center">
|
|
@@ -1965,11 +1965,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1965
1965
|
${d}
|
|
1966
1966
|
</div>
|
|
1967
1967
|
</div>
|
|
1968
|
-
`,h}function
|
|
1969
|
-
<div class="__crossx-card __crossx-card--migration" style="${
|
|
1968
|
+
`,h}function Ei(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],o=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${o} ${i} ${a}:${c}`}function Ii(s,e,r){const t=s,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?Ei(o):null,a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
1969
|
+
<div class="__crossx-card __crossx-card--migration" style="${ue(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1970
1970
|
<div class="__crossx-header">
|
|
1971
1971
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
1972
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1972
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1973
1973
|
</div>
|
|
1974
1974
|
<hr class="__crossx-divider">
|
|
1975
1975
|
<div class="__crossx-pin-center">
|
|
@@ -1980,54 +1980,54 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1980
1980
|
<div class="__crossx-pin-dot" aria-hidden="true">●</div>
|
|
1981
1981
|
</div>
|
|
1982
1982
|
<div class="__crossx-pin-lock-messages">
|
|
1983
|
-
<p class="__crossx-pin-lock-message">${n?
|
|
1983
|
+
<p class="__crossx-pin-lock-message">${n?r:"Please try again after the lock expires."}</p>
|
|
1984
1984
|
${i?`<p class="__crossx-pin-lock-secondary">(Available from ${i})</p>`:""}
|
|
1985
1985
|
</div>
|
|
1986
1986
|
</div>
|
|
1987
1987
|
</div>
|
|
1988
|
-
`,{overlay:a,startCountdown:l=>{if(n||!o)return()=>{};const h=setInterval(()=>{Date.now()>=o&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function
|
|
1988
|
+
`,{overlay:a,startCountdown:l=>{if(n||!o)return()=>{};const h=setInterval(()=>{Date.now()>=o&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function Ai(s){const r=[s.check1,s.check2].map((t,n)=>`
|
|
1989
1989
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
1990
|
-
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${
|
|
1991
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
1990
|
+
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${Pi}</div>
|
|
1991
|
+
<span class="__crossx-pw-notice-item-text">${W(t)}</span>
|
|
1992
1992
|
</div>
|
|
1993
1993
|
`).join("");return`
|
|
1994
1994
|
<div class="__crossx-header">
|
|
1995
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
1996
|
-
<p class="__crossx-pw-subtitle">${
|
|
1997
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1995
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${W(s.title)}</p>
|
|
1996
|
+
<p class="__crossx-pw-subtitle">${W(s.headerSubtitle)}</p>
|
|
1997
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
1998
1998
|
</div>
|
|
1999
1999
|
<hr class="__crossx-divider">
|
|
2000
2000
|
<div class="__crossx-pw-body">
|
|
2001
2001
|
<div class="__crossx-pw-fields __crossx-pw-fields--notice">
|
|
2002
2002
|
<div class="__crossx-pw-notice-header">
|
|
2003
2003
|
<div class="__crossx-pw-notice-title-row">
|
|
2004
|
-
<span class="__crossx-pw-notice-icon">${
|
|
2005
|
-
<p class="__crossx-pw-notice-title">${
|
|
2004
|
+
<span class="__crossx-pw-notice-icon">${Ci}</span>
|
|
2005
|
+
<p class="__crossx-pw-notice-title">${W(s.noticeTitle)}</p>
|
|
2006
2006
|
</div>
|
|
2007
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2007
|
+
<p class="__crossx-pw-notice-desc">${W(s.noticeDesc)}</p>
|
|
2008
2008
|
</div>
|
|
2009
2009
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2010
|
-
${
|
|
2010
|
+
${r}
|
|
2011
2011
|
</div>
|
|
2012
2012
|
</div>
|
|
2013
2013
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2014
|
-
data-next-label="${
|
|
2015
|
-
data-submit-label="${
|
|
2016
|
-
${
|
|
2014
|
+
data-next-label="${W(s.nextButton)}"
|
|
2015
|
+
data-submit-label="${W(s.submitButton)}">
|
|
2016
|
+
${W(s.nextButton)}
|
|
2017
2017
|
</button>
|
|
2018
2018
|
</div>
|
|
2019
2019
|
<div class="__crossx-home-indicator"></div>
|
|
2020
|
-
`}function
|
|
2021
|
-
${
|
|
2020
|
+
`}function Jt(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${W(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${W(s.subtitle)}</p>`:"",o=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${W(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',i=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2021
|
+
${Rs}
|
|
2022
2022
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2023
2023
|
</p>`:"",a=e?" --locked":"",c=Array.from({length:6},(l,d)=>`<input class="__crossx-pin6-box${a}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${d+1}"${e?" disabled":""}>`).join("");return`
|
|
2024
2024
|
<div class="__crossx-header">
|
|
2025
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2025
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${W(s.title)}</p>
|
|
2026
2026
|
${t}
|
|
2027
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2027
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ce}</button>
|
|
2028
2028
|
</div>
|
|
2029
2029
|
<hr class="__crossx-divider">
|
|
2030
|
-
<div class="__crossx-pin6-body"${
|
|
2030
|
+
<div class="__crossx-pin6-body"${r}>
|
|
2031
2031
|
${n}
|
|
2032
2032
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
2033
2033
|
${c}
|
|
@@ -2036,14 +2036,14 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2036
2036
|
${i}
|
|
2037
2037
|
</div>
|
|
2038
2038
|
<div class="__crossx-home-indicator"></div>
|
|
2039
|
-
`}function
|
|
2040
|
-
<div class="__crossx-card __crossx-card--pin6" style="${
|
|
2039
|
+
`}function Ts(s,e){const r=document.createElement("div");return r.id=te,r.innerHTML=`
|
|
2040
|
+
<div class="__crossx-card __crossx-card--pin6" style="${ue(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2041
2041
|
${e}
|
|
2042
2042
|
</div>
|
|
2043
|
-
`,
|
|
2043
|
+
`,r}function Ti(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((o,i)=>i===0||o===(r[i-1]+1)%10),n=r.every((o,i)=>i===0||o===(r[i-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function Ri(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function Vt(s,e,r,t,n,o){let i=!!(o&&o>Date.now()),a=!1;const c=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),l=()=>s.querySelector("#__crossx-pin6-boxes"),d=()=>s.querySelector("#__crossx-pin6-error"),h=()=>s.querySelector("#__crossx-pin6-lock-msg"),w=()=>s.querySelector("#__crossx-pin6-lock-countdown"),p=()=>s.querySelector(".__crossx-pin6-body"),m=()=>c().map(b=>b.value).join(""),v=b=>{i=b,c().forEach(P=>{P.disabled=b,P.classList.toggle("--locked",b)})},y=()=>{const b=d();b&&(b.textContent="")},E=b=>{const P=d();P&&(P.textContent=b);const C=l();C==null||C.classList.add("--shake"),setTimeout(()=>C==null?void 0:C.classList.remove("--shake"),500),c().forEach(F=>{F.value=""}),setTimeout(()=>{var F;return(F=c()[0])==null?void 0:F.focus()},50)},k=b=>{var K;v(!0),c().forEach(G=>{G.value=""});const P=d();if(P&&(P.textContent="Too many failed attempts. Please wait."),!h()){const G=document.createElement("p");G.className="__crossx-pin6-lock-msg",G.id="__crossx-pin6-lock-msg",G.innerHTML=`${Rs}<span id="__crossx-pin6-lock-countdown"></span>`;const D=d();D?D.insertAdjacentElement("afterend",G):(K=p())==null||K.appendChild(G)}const C=()=>{var R;const G=b-Date.now(),D=w();G<=0?(clearInterval(F),v(!1),(R=h())==null||R.remove(),P&&(P.textContent=""),setTimeout(()=>{var O;return(O=c()[0])==null?void 0:O.focus()},50)):D&&(D.textContent=` ${Ri(G)}`)},F=setInterval(C,1e3);C();const V=new MutationObserver(()=>{document.contains(s)||(clearInterval(F),V.disconnect())});V.observe(document.body,{childList:!0,subtree:!1})},B=async()=>{if(i||a)return;const b=m();if(b.length===6){a=!0,c().forEach(P=>{P.disabled=!0});try{if(n){const P=await n(b);P.ok?e(b):P.lockExpiresAt?k(P.lockExpiresAt):E(P.error??"Incorrect PIN. Please try again.")}else e(b)}catch(P){t&&t(P)}finally{a=!1,i||c().forEach(P=>{P.disabled=!1})}}};o&&o>Date.now()?k(o):setTimeout(()=>{var b;return(b=c()[0])==null?void 0:b.focus()},100),c().forEach((b,P)=>{b.addEventListener("input",()=>{var F;const C=b.value.replace(/\D/g,"").slice(-1);b.value=C,y(),C&&P<5&&((F=c()[P+1])==null||F.focus()),m().length===6&&setTimeout(B,80)}),b.addEventListener("keydown",C=>{var F,V;if(C.key==="Backspace"){if(C.preventDefault(),b.value)b.value="";else if(P>0){const K=c()[P-1];K.value="",K.focus()}}else C.key==="ArrowLeft"&&P>0?(C.preventDefault(),(F=c()[P-1])==null||F.focus()):C.key==="ArrowRight"&&P<5?(C.preventDefault(),(V=c()[P+1])==null||V.focus()):C.key==="Escape"&&r()}),b.addEventListener("paste",C=>{var K,G;C.preventDefault();const F=(((K=C.clipboardData)==null?void 0:K.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!F)return;const V=c();F.split("").forEach((D,R)=>{V[R]&&(V[R].value=D)}),(G=V[Math.min(F.length-1,5)])==null||G.focus(),y(),m().length===6&&setTimeout(B,80)}),b.addEventListener("focus",()=>b.select())})}const Rs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2044
2044
|
<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"/>
|
|
2045
|
-
</svg>`,
|
|
2045
|
+
</svg>`,Pi=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2046
2046
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2047
|
-
</svg>`,
|
|
2047
|
+
</svg>`,Ci=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2048
2048
|
<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"/>
|
|
2049
|
-
</svg>`;function po(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((h,m)=>{t[m]&&(t[m].value=h)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class fo{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Ps(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Ps(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var E;pe();const o=[...e],i=Qn(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const S=y.dataset.walletAddress??"",C=parseInt(y.dataset.walletIndex??"0",10);d({address:S,index:C})})})})();const g=i.querySelector("#__crossx-add-wallet-btn");g&&g.addEventListener("click",async()=>{g.disabled=!0;try{const y=await s();o.push(y);const S=i.querySelector("#__crossx-wallet-list");if(S){const C=document.createElement("button");C.className="__crossx-wallet-item",C.dataset.walletIndex=String(y.index),C.dataset.walletAddress=y.address,C.innerHTML=`<span class="__crossx-wallet-addr">${te(y.address)}</span>`,C.addEventListener("click",()=>d(y)),S.appendChild(C),C.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{g.disabled=!1}}),(E=i.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(){return new Promise(e=>{var a,c,l;pe();const s=so(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",h=>h.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;pe();const s=ro(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinSetupPrompt(e){return new Promise(s=>{pe();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},o={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},i={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=Cs(this.tokens,ao(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=C=>{d(),s(C)},m=()=>{d(),s(null)},g=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},E=C=>{var U;g.innerHTML=bt({title:i.title,headerSubtitle:i.headerSubtitle}),(U=g.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",m),vt(g,b=>{b===C?h(C):y(o.mismatchError)},m)},y=C=>{var U;g.innerHTML=bt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:C}),(U=g.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",m),vt(g,b=>{const P=co(b,w);P?y(P):E(b)},m)};(()=>{var q;const C=Array.from(g.querySelectorAll(".__crossx-pw-notice-item")),U=g.querySelector("#__crossx-pin-notice-next"),b=new Set;U.removeAttribute("disabled");const P=U.dataset.nextLabel??"Next",k=U.dataset.submitLabel??"I Understand",W=()=>{const D=b.size===C.length;U.classList.toggle("--disabled",!D),U.textContent=D?k:P},z=(D,R)=>{if(b.has(R))return;const N=D.querySelector(`#__crossx-notice-check-${R}`);b.add(R),N.classList.add("--checked"),D.setAttribute("aria-checked","true"),W()},G=(D,R)=>{if(!b.has(R))return;const N=D.querySelector(`#__crossx-notice-check-${R}`);b.delete(R),N.classList.remove("--checked"),D.setAttribute("aria-checked","false"),W()};C.forEach(D=>{const R=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{b.has(R)?G(D,R):z(D,R)}),D.addEventListener("keydown",N=>{(N.key===" "||N.key==="Enter")&&(N.preventDefault(),b.has(R)?G(D,R):z(D,R))})}),U.addEventListener("click",()=>{if(b.size===C.length){y(e==null?void 0:e.errorMessage);return}const D=C.find(N=>{const _=parseInt(N.dataset.checkIndex??"0",10);return!b.has(_)});if(!D)return;const R=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),z(D,R)},400)}),(q=g.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",m)})(),a.addEventListener("click",C=>{C.target===a&&m()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;pe();const n=this.messages,o=(e==null?void 0:e.verifyMode)===!0,i=o?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=o?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=Cs(this.tokens,bt({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt})),l=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(c);let d=!1;const h=()=>{d||(d=!0,c.remove(),document.body.style.overflow=l)},m=S=>{h(),s(S)},g=()=>{h(),s(null)},w=S=>{h(),t(S)},E=c.querySelector(".__crossx-card");(y=E.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",g),vt(E,m,g,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",S=>{S.target===c&&g()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;pe();const t=no(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};po(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,s){return new Promise(t=>{var l;pe();const{overlay:n,startCountdown:o}=io(this.tokens,e,s);document.body.appendChild(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;pe();const t=zn(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var m;d.stopPropagation();const h=l.dataset.copy;h&&((m=navigator.clipboard)==null||m.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{pe();const n=Jn(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,h;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",m=>{m.target===n&&a()});const l=m=>{m.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(jn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;pe();let t;e.type==="sign-message"?t=Yn(e,this.tokens):e.type==="sign-typed-data"?t=Xn(e,this.tokens):e.type==="sign"?t=Gn(e,this.tokens):t=qn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",m=>{var w;m.stopPropagation();const g=h.dataset.copy;g&&((w=navigator.clipboard)==null||w.writeText(g).catch(()=>{}))})}),t.addEventListener("click",h=>{h.target===t&&i()});const a=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class _o{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function xo(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"&&Lt.isAvailable()?new Lt:new nr,a=new kn,c=new Cn,l=new Te,d=new _o,h=new At;let m;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),m=new Ln(i,h)):(u.log("[CROSSx] Remote Wallet Provider 사용"),m=new Be(n,i,c,d,h));const g=new Ue(n,c),w=new fo(r.theme??"light",r.themeTokens),E=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w;return new Ge(t,n,i,a,c,l,m,d,E,g,h)}return ne.CROSSxError=f,ne.CROSSxEthereumProvider=St,ne.CROSSxSDK=Ge,ne.ChainId=$s,ne.ErrorCode=p,ne.createCROSSxSDK=xo,Object.defineProperty(ne,Symbol.toStringTag,{value:"Module"}),ne}({});
|
|
2049
|
+
</svg>`;function Oi(s,e,r){var n;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&r()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((h,w)=>{t[w]&&(t[w].value=h)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class Ni{constructor(e="light",r){this.theme=e,this.overrides=r,this.tokens=vs(e,r)}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=vs(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise(n=>{var v;we();const o=[...e],i=mi(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const E=y.dataset.walletAddress??"",k=parseInt(y.dataset.walletIndex??"0",10);d({address:E,index:k})})})})();const p=i.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const y=await r();o.push(y);const E=i.querySelector("#__crossx-wallet-list");if(E){const k=document.createElement("button");k.className="__crossx-wallet-item",k.dataset.walletIndex=String(y.index),k.dataset.walletAddress=y.address,k.innerHTML=`<span class="__crossx-wallet-addr">${re(y.address)}</span>`,k.addEventListener("click",()=>d(y)),E.appendChild(k),k.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(v=i.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const m=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",m),h())};document.addEventListener("keydown",m)})}showLoginSelector(){return new Promise(e=>{var a,c,l;we();const r=bi(this.tokens);document.body.appendChild(r);const t=()=>r.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=r.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=r.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),r.addEventListener("click",d=>{d.target===r&&o()}),r.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",h=>h.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;we();const r=Si(this.tokens);document.body.appendChild(r);const t=()=>r.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=r.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=r.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=r.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),r.addEventListener("click",d=>{d.target===r&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinSetupPrompt(e){return new Promise(r=>{we();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},o={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},i={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=Ts(this.tokens,Ai(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=k=>{d(),r(k)},w=()=>{d(),r(null)},p=a.querySelector(".__crossx-card"),m={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;p.innerHTML=Jt({title:i.title,headerSubtitle:i.headerSubtitle}),(B=p.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",w),Vt(p,b=>{b===k?h(k):y(o.mismatchError)},w)},y=k=>{var B;p.innerHTML=Jt({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:k}),(B=p.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",w),Vt(p,b=>{const P=Ti(b,m);P?y(P):v(b)},w)};(()=>{var G;const k=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),B=p.querySelector("#__crossx-pin-notice-next"),b=new Set;B.removeAttribute("disabled");const P=B.dataset.nextLabel??"Next",C=B.dataset.submitLabel??"I Understand",F=()=>{const D=b.size===k.length;B.classList.toggle("--disabled",!D),B.textContent=D?C:P},V=(D,R)=>{if(b.has(R))return;const O=D.querySelector(`#__crossx-notice-check-${R}`);b.add(R),O.classList.add("--checked"),D.setAttribute("aria-checked","true"),F()},K=(D,R)=>{if(!b.has(R))return;const O=D.querySelector(`#__crossx-notice-check-${R}`);b.delete(R),O.classList.remove("--checked"),D.setAttribute("aria-checked","false"),F()};k.forEach(D=>{const R=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{b.has(R)?K(D,R):V(D,R)}),D.addEventListener("keydown",O=>{(O.key===" "||O.key==="Enter")&&(O.preventDefault(),b.has(R)?K(D,R):V(D,R))})}),B.addEventListener("click",()=>{if(b.size===k.length){y(e==null?void 0:e.errorMessage);return}const D=k.find(O=>{const _=parseInt(O.dataset.checkIndex??"0",10);return!b.has(_)});if(!D)return;const R=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),V(D,R)},400)}),(G=p.querySelector("#__crossx-close-btn"))==null||G.addEventListener("click",w)})(),a.addEventListener("click",k=>{k.target===a&&w()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var y;we();const n=this.messages,o=(e==null?void 0:e.verifyMode)===!0,i=o?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=o?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=Ts(this.tokens,Jt({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt})),l=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(c);let d=!1;const h=()=>{d||(d=!0,c.remove(),document.body.style.overflow=l)},w=E=>{h(),r(E)},p=()=>{h(),r(null)},m=E=>{h(),t(E)},v=c.querySelector(".__crossx-card");(y=v.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",p),Vt(v,w,p,m,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",E=>{E.target===c&&p()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var a;we();const t=vi(this.tokens,e);document.body.appendChild(t);const n=()=>t.remove(),o=c=>{n(),r(c)},i=()=>{n(),r(null)};Oi(t,o,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;we();const{overlay:n,startCountdown:o}=Ii(this.tokens,e,r);document.body.appendChild(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;we();const t=hi(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var w;d.stopPropagation();const h=l.dataset.copy;h&&((w=navigator.clipboard)==null||w.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,r){return new Promise(t=>{we();const n=fi(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,h;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",w=>{w.target===n&&a()});const l=w=>{w.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{i||(pi(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(r=>{var c,l,d;we();let t;e.type==="sign-message"?t=_i(e,this.tokens):e.type==="sign-typed-data"?t=gi(e,this.tokens):e.type==="sign"?t=ci(e,this.tokens):t=li(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),r(!0)},i=()=>{n(),r(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",w=>{var m;w.stopPropagation();const p=h.dataset.copy;p&&((m=navigator.clipboard)==null||m.writeText(p).catch(()=>{}))})}),t.addEventListener("click",h=>{h.target===t&&i()});const a=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class ki{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}}function Li(s,e){s.debug;const r=Qe.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},o=t.authMode!=="cookie"&&ar.isAvailable();!o&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new ar(s.projectId):new js,a=new Vo,c=new Zo,l=new Ce,d=new ki,h=new tr;let w;s.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),w=new Qo(i,h)):(u.log("[CROSSx] Remote Wallet Provider 사용"),w=new Ye(n,i,c,d,h));const p=new je(n,c),m=new Ni(s.theme??"light",s.themeTokens),v=e!=null&&e.wrapConfirmation?e.wrapConfirmation(m):m;return new et(t,n,i,a,c,l,w,d,v,p,h)}return oe.CROSSxError=x,oe.CROSSxEthereumProvider=zt,oe.CROSSxSDK=et,oe.ChainId=Ns,oe.ErrorCode=f,oe.createCROSSxSDK=Li,Object.defineProperty(oe,Symbol.toStringTag,{value:"Module"}),oe}({});
|