@nexus-cross/crossx-sdk-core 1.3.4 → 1.3.6
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/__tests__/utils/parseOAuthDeeplink.test.d.ts +20 -0
- package/dist/__tests__/utils/parseOAuthDeeplink.test.d.ts.map +1 -0
- package/dist/adapters/oauth/BrowserOAuthAdapter.d.ts.map +1 -1
- package/dist/core/usecases/SignInUseCase.d.ts +15 -0
- package/dist/core/usecases/SignInUseCase.d.ts.map +1 -1
- package/dist/core/utils/parseOAuthDeeplink.d.ts +70 -0
- package/dist/core/utils/parseOAuthDeeplink.d.ts.map +1 -0
- package/dist/crossx.global +20 -20
- package/dist/index.cjs +41 -41
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +809 -686
- package/dist/sdk/CROSSxSDK.d.ts +18 -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/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";var $s=Object.defineProperty;var Bs=(r,e,s)=>e in r?$s(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var I=(r,e,s)=>Bs(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("jose");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.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.BROADCAST_FAILED="BROADCAST_FAILED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",r.PIN_CANCELLED="PIN_CANCELLED",r.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",r.PIN_LOCKED="PIN_LOCKED",r.HMAC_REQUIRED="HMAC_REQUIRED",r.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",r.WITHDRAW_FAILED="WITHDRAW_FAILED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class m extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const 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}},Us=Object.fromEntries(Object.entries(ze).map(([r,e])=>[r,e.caipId])),Hs=new Map(Object.values(ze).map(r=>[r.caipId,r]));new Map(Object.values(ze).map(r=>[r.chainId,r]));const Fs={symbol:"",decimals:18};function Ze(r){var e;return((e=Hs.get(r))==null?void 0:e.nativeCurrency)??Fs}class ts{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new m(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...s))}_caip2ToHex(e){const s=e.split(":");return`0x${parseInt(s[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let Ee=null;function Et(r){Ee=r}const d={log(...r){if(Ee){Ee.log(...r);return}},warn(...r){if(Ee){Ee.warn(...r);return}},error(...r){if(Ee){Ee.error(...r);return}}},Gs={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간"},ss={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from"},Ws={ko:Gs,en:ss};function It(r="en",e){return Ws[r]??ss}const At="crossx_access_token",Tt="crossx_refresh_token",Rt="crossx_user_info";class qs{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new m(p.AUTH_FAILED,`${s} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new m(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:u,authApiUrl:h}=this.config,g=`${u}${l}`;d.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const f=await this.oauth.openAuth({authUrl:g,expectedOrigin:new URL(u).origin});d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",f.length,")");const{accessToken:w,refreshToken:v}=await this.exchangeFirebaseToken(f,h);let y,S;try{const U=this.crypto.decodeJWT(f);S=(n=U.firebase)==null?void 0:n.sign_in_provider;const O=((o=U.firebase)==null?void 0:o.identities)??{};S==="google.com"?y=(i=O["google.com"])==null?void 0:i[0]:S==="apple.com"&&(y=(a=O["apple.com"])==null?void 0:a[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",S,"hasProviderSub:",!!y)}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const U=this.crypto.decodeJWT(w);d.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const O=await this.crypto.verifyJWT(w);if(t=O.signatureVerified??!1,!O.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const V=O.payload;s={id:V.sub,email:V.email,signInProvider:S,providerSub:y},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,w),v&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,v):v&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const U=this.crypto.decodeJWT(f);s={id:U.sub,email:U.email,signInProvider:S,providerSub:y},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}d.log("[CROSSx] 사용자 정보 — id:",s.id);const C=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(this.STORAGE_KEY_USER,C),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return d.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return d.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`;d.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new m(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return d.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl: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"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new m(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,c);const l=this.extractRefreshToken(a);l&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,l)}return d.log("[CROSSx] silentRefresh 성공"),c}async executeWithJWT(e,s){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!s)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Rt);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(At);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Tt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Rt),await this.storage.remove(At),await this.storage.remove(Tt),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof m&&o.code===p.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof m&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}class Ks{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Vs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new m(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class ht{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let o=0;o<s.length;o++)n[o]=s[o]^t[o];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class zs{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new m(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 Ge={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 Ge?Ge[e]:null}function Js(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Ys(r);if(e)return e}}catch{}return Ge.production}const Xs=2e3,kt=6e4,Zs=1e3,Qs=1e4,er="0x77359400",Pt="0x3B9ACA00",Ot=130,Nt=6,Ct=18,tr=5*60*1e3,sr=30*1e3,re=class re extends js{constructor(e,s,t,n,o,i,a,c,l,u,h){var g;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Et(e.logger),this.confirmation=l,this.pinStore=h??new ht,this.chainRegistry=u,this.jsonRpc=new zs(u,o),this.signInUseCase=new qs(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ks(this.internalConfig,t,c),this.migrateWalletUseCase=new Vs(t,a),(g=a.setOnUnauthorized)==null||g.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 s,t;d.log("[CROSSx SDK] v1.3.4 초기화 중..."),this.confirmation.setMessages(It(this._config.locale));try{const n=Js();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const o=await this.signInUseCase.restoreSession();if(o!=null&&o.success){this.applyAuthResult(o);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(i){if(!(i instanceof m&&i.code===p.PIN_CANCELLED))throw i;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(o!=null&&o.success)}),o??null}catch(n){throw new m(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new m(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new m(p.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address: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 m&&t.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new m(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof m&&s.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof m?s:new m(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.walletProvider.getAddresses(this.userId);return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(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 m?e:new m(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof m?s:new m(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(It(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(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 m(p.USER_REJECTED,"User rejected the message signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof m?i:new m(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new m(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");re.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 m(p.USER_REJECTED,"User rejected the typed data signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return re.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof m?i:new m(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(re.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(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=Ze(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return re.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(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=Ze(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(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??Zs,o=Qs,i=t.timeoutMs??kt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,o)}throw new m(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var v,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??Xs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??kt,u=Ze(e),h=s.from??"";let g,f;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{g=S;const C=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),U=s.value?BigInt(s.value):0n,O=re.formatTxAmount(s.value,u.symbol,u.decimals),V=re.formatTxAmount("0x"+C.toString(16),u.symbol,u.decimals),W=re.formatTxAmount("0x"+(U+C).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:S.from,to:S.to??s.to,amount:O,fees:V,total:W,nativeSymbol:u.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(f=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:h,to:s.to,amount:re.formatTxAmount(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:s.to},w),f)throw f;return{chainId:e,txHash:a,receipt:g}}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 m(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof m?n:new m(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 m(p.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new m(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 m(p.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(p.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof m)throw t;const n=t instanceof Error?t.message:String(t);throw new m(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:re.formatWei(n),chainId:e}}catch(t){if(t instanceof m)throw t;const n=t instanceof Error?t.message:String(t);throw new m(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(Ct),n=s/t,i=(s%t).toString().padStart(Ct,"0").replace(/0+$/,"").slice(0,Nt);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new ts(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof m)throw n;const o=n instanceof Error?n.message:String(n);throw new m(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 c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const h=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});if(h===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const g=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,h,e));if(!g){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(g.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const f=g.pinStatus;if(i=f.maxAttempts,o=i-f.remainingAttempts,f.remainingAttempts===0&&f.lockExpiresAt){const w=f.lockExpiresAt*1e3,v=Math.max(1,Math.round((w-Date.now())/1e3)),y=v<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${v}초, 메시지: ${y}`),await this.confirmation.showRecoveryPinLockedPrompt(v,y),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(g){if(!(g instanceof m))throw g;if(g.code===p.MIGRATION_PIN_LOCKED){const f=g.details;if(i=(f==null?void 0:f.maxAttempts)??5,(f==null?void 0:f.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((f==null?void 0:f.lockExpiresAt)??0)*1e3,v=Math.max(1,Math.round((w-Date.now())/1e3)),y=v<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${v}초`),await this.confirmation.showRecoveryPinLockedPrompt(v,y),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",g),g}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const h=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof m&&h.code===p.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}async withResolvedGasAndFee(e,s){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,h,g]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,o?this.estimateGas(e,s):null,i?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=h,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const f=g;if(f){const w=Pt;c.maxFeePerGas="0x"+(BigInt(f)+BigInt(w)).toString(16),c.maxPriorityFeePerGas=w,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=er,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Pt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=re.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new m(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 m(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Ot)throw new m(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Ot} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new m(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new m(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new m(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof m)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var 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=re.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new m(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new m(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s});if(!i)throw new m(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}const o=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof m){if(c.code===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 m(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(o),d.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(d.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,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let s,t;try{return await e()}catch(n){if(n instanceof m)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(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",s),this.pinStore.clear(),await this.ensureVerifiedPin(s,t),t=void 0;try{return await e()}catch(n){if(n instanceof m){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 m(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 m(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Et(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};re.OFFCHAIN_CHAIN_ID="0";let We=re;class rr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return d.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw d.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Qe="crossx-sdk",nr=1,de="data",Se="keys",$e="aes-primary",or=12;class Lt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,nr);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(de)||o.createObjectStore(de),o.objectStoreNames.contains(Se)||o.createObjectStore(Se)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Se,$e);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Se,$e,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Qe)return null;try{const e=await this.openDB(Qe),s=e.transaction([Se,de],"readonly"),t=s.objectStore(Se).get($e),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=s.objectStore(de).getAll(),i=s.objectStore(de).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(Se,$e,n);for(let l=0;l<c.length;l++)await this.idbPut(de,String(c[l]),a[l]);return indexedDB.deleteDatabase(Qe),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(or);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(de,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(de,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return d.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(de,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(de)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ge(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function z(r,e,s=""){const t=pt(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 rs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ge(r.outputLen),ge(r.blockLen)}function ke(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ns(r,e){z(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function ir(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 et(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ue(r,e){return r<<32-e|r>>>e}const ar=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function lr(r){for(let e=0;e<r.length;e++)r[e]=cr(r[e]);return r}const Dt=ar?r=>r:lr,os=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Me(r){if(z(r),os)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=dr[r[s]];return e}const fe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Mt(r){if(r>=fe._0&&r<=fe._9)return r-fe._0;if(r>=fe.A&&r<=fe.F)return r-(fe.A-10);if(r>=fe.a&&r<=fe.f)return r-(fe.a-10)}function qe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(os)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=Mt(r.charCodeAt(o)),a=Mt(r.charCodeAt(o+1));if(i===void 0||a===void 0){const c=r[o]+r[o+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+o)}t[n]=i*16+a}return t}function ve(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];z(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function is(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 as(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 ur=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function hr(r,e,s){return r&e^~r&s}function pr(r,e,s){return r&e^r&s^e&s}class fr{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=et(this.buffer)}update(e){ke(this),z(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=et(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){ke(this),ns(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=et(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){const{buffer:e,outputLen: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 me=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Be=BigInt(2**32-1),$t=BigInt(32);function _r(r,e=!1){return e?{h:Number(r&Be),l:Number(r>>$t&Be)}:{h:Number(r>>$t&Be)|0,l:Number(r&Be)|0}}function xr(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}=_r(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const gr=(r,e,s)=>r<<s|e>>>32-s,mr=(r,e,s)=>e<<s|r>>>32-s,wr=(r,e,s)=>e<<s-32|r>>>64-s,yr=(r,e,s)=>r<<s-32|e>>>64-s,br=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]),we=new Uint32Array(64);class vr extends fr{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)we[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const g=we[h-15],f=we[h-2],w=ue(g,7)^ue(g,18)^g>>>3,v=ue(f,17)^ue(f,19)^f>>>10;we[h]=v+we[h-7]+w+we[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const g=ue(a,6)^ue(a,11)^ue(a,25),f=u+g+hr(a,c,l)+br[h]+we[h]|0,v=(ue(t,2)^ue(t,13)^ue(t,22))+pr(t,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=t,t=f+v|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,o,i,a,c,l,u)}roundClean(){Pe(we)}destroy(){this.set(0,0,0,0,0,0,0,0),Pe(this.buffer)}}class Sr extends vr{constructor(){super(32);I(this,"A",me[0]|0);I(this,"B",me[1]|0);I(this,"C",me[2]|0);I(this,"D",me[3]|0);I(this,"E",me[4]|0);I(this,"F",me[5]|0);I(this,"G",me[6]|0);I(this,"H",me[7]|0)}}const Er=is(()=>new Sr,ur(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ft=BigInt(0),ct=BigInt(1);function Ke(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function cs(r){if(typeof r=="bigint"){if(!Fe(r))throw new Error("positive bigint expected, got "+r)}else ge(r);return r}function Ue(r){const e=cs(r).toString(16);return e.length&1?"0"+e:e}function ls(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ft:BigInt("0x"+r)}function je(r){return ls(Me(r))}function ds(r){return ls(Me(Ir(z(r)).reverse()))}function _t(r,e){ge(e),r=cs(r);const s=qe(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function us(r,e){return _t(r,e).reverse()}function Ir(r){return Uint8Array.from(r)}const Fe=r=>typeof r=="bigint"&&ft<=r;function Ar(r,e,s){return Fe(r)&&Fe(e)&&Fe(s)&&e<=r&&r<s}function Tr(r,e,s,t){if(!Ar(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Rr(r){let e;for(e=0;r>ft;r>>=ct,e+=1);return e}const xt=r=>(ct<<BigInt(r))-ct;function kr(r,e,s){if(ge(r,"hashLen"),ge(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),u=0;const h=()=>{c.fill(1),l.fill(0),u=0},g=(...y)=>s(l,ve(c,...y)),f=(y=n)=>{l=g(o,y),c=g(),y.length!==0&&(l=g(i,y),c=g())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const S=[];for(;y<e;){c=g();const C=c.slice();S.push(C),y+=c.length}return ve(...S)};return(y,S)=>{h(),f(y);let C;for(;!(C=S(w()));)f();return h(),C}}function gt(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 Bt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ne=BigInt(0),ee=BigInt(1),Ie=BigInt(2),hs=BigInt(3),ps=BigInt(4),fs=BigInt(5),Pr=BigInt(7),_s=BigInt(8),Or=BigInt(9),xs=BigInt(16);function le(r,e){const s=r%e;return s>=ne?s:e+s}function ae(r,e,s){let t=r;for(;e-- >ne;)t*=t,t%=s;return t}function Ut(r,e){if(r===ne)throw new Error("invert: expected non-zero number");if(e<=ne)throw new Error("invert: expected positive modulus, got "+e);let s=le(r,e),t=e,n=ne,o=ee;for(;s!==ne;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==ee)throw new Error("invert: does not exist");return le(n,e)}function mt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function gs(r,e){const s=(r.ORDER+ee)/ps,t=r.pow(e,s);return mt(r,t,e),t}function Nr(r,e){const s=(r.ORDER-fs)/_s,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 mt(r,a,e),a}function Cr(r){const e=Ye(r),s=ms(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Pr)/xs;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const h=a.mul(l,n),g=a.mul(l,o),f=a.eql(a.sqr(u),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(g,h,w);const v=a.eql(a.sqr(u),c),y=a.cmov(l,u,v);return mt(a,y,c),y}}function ms(r){if(r<hs)throw new Error("sqrt is not defined for small field");let e=r-ee,s=0;for(;e%Ie===ne;)e/=Ie,s++;let t=Ie;const n=Ye(r);for(;Ht(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return gs;let o=n.pow(t,e);const i=(e+ee)/Ie;return function(c,l){if(c.is0(l))return l;if(Ht(c,l)!==1)throw new Error("Cannot find square root");let u=s,h=c.mul(c.ONE,o),g=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let w=1,v=c.sqr(g);for(;!c.eql(v,c.ONE);)if(w++,v=c.sqr(v),w===u)throw new Error("Cannot find square root");const y=ee<<BigInt(u-w-1),S=c.pow(h,y);u=w,h=c.sqr(S),g=c.mul(g,h),f=c.mul(f,S)}return f}}function Lr(r){return r%ps===hs?gs:r%_s===fs?Nr:r%xs===Or?Cr(r):ms(r)}const Dr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Dr.reduce((t,n)=>(t[n]="function",t),e);return gt(r,s),r}function $r(r,e,s){if(s<ne)throw new Error("invalid exponent, negatives unsupported");if(s===ne)return r.ONE;if(s===ee)return e;let t=r.ONE,n=e;for(;s>ne;)s&ee&&(t=r.mul(t,n)),n=r.sqr(n),s>>=ee;return t}function ws(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 Ht(r,e){const s=(r.ORDER-ee)/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 Br(r,e){e!==void 0&&ge(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ur{constructor(e,s={}){I(this,"ORDER");I(this,"BITS");I(this,"BYTES");I(this,"isLE");I(this,"ZERO",ne);I(this,"ONE",ee);I(this,"_lengths");I(this,"_sqrt");I(this,"_mod");var i;if(e<=ne)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Br(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 le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ne<=e&&e<this.ORDER}is0(e){return e===ne}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return le(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return le(e*e,this.ORDER)}add(e,s){return le(e+s,this.ORDER)}sub(e,s){return le(e-s,this.ORDER)}mul(e,s){return le(e*s,this.ORDER)}pow(e,s){return $r(this,e,s)}div(e,s){return le(e*Ut(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 Ut(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Lr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?us(e,this.BYTES):_t(e,this.BYTES)}fromBytes(e,s=!1){z(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?ds(e):je(e);if(a&&(c=le(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ws(this,e)}cmov(e,s,t){return t?s:e}}function Ye(r,e={}){return new Ur(r,e)}function ys(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 bs(r){const e=ys(r);return e+Math.ceil(e/2)}function Hr(r,e,s=!1){z(r);const t=r.length,n=ys(e),o=bs(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?ds(r):je(r),a=le(i,e-ee)+ee;return s?us(a,n):_t(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oe=BigInt(0),Ae=BigInt(1);function Ve(r,e){const s=e.negate();return r?s:e}function Ft(r,e){const s=ws(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function vs(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tt(r,e){vs(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=xt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Gt(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+=Ae);const l=e*t,u=l+Math.abs(a)-1,h=a===0,g=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:g,isNegF:f,offsetF:l}}const st=new WeakMap,Ss=new WeakMap;function rt(r){return Ss.get(r)||1}function Wt(r){if(r!==Oe)throw new Error("invalid wNAF")}class Fr{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>Oe;)s&Ae&&(t=t.add(n)),n=n.double(),s>>=Ae;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=tt(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=tt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:g,offsetF:f}=Gt(t,a,i);t=c,u?o=o.add(Ve(g,s[f])):n=n.add(Ve(h,s[l]))}return Wt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=tt(e,this.bits);for(let i=0;i<o.windows&&t!==Oe;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Gt(t,i,o);if(t=a,!l){const h=s[c];n=n.add(u?h.negate():h)}}return Wt(t),n}getPrecomputes(e,s,t){let n=st.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),st.set(s,n))),n}cached(e,s,t){const n=rt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=rt(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){vs(s,this.bits),Ss.set(e,s),st.delete(e)}hasCache(e){return rt(e)!==1}}function Gr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Oe||t>Oe;)s&Ae&&(o=o.add(n)),t&Ae&&(i=i.add(n)),n=n.double(),s>>=Ae,t>>=Ae;return{p1:o,p2:i}}function qt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Mr(e),e}else return Ye(r,{isLE:s})}function Wr(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>Oe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=qt(e.p,s.Fp,t),o=qt(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 qr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Es{constructor(e,s){I(this,"oHash");I(this,"iHash");I(this,"blockLen");I(this,"outputLen");I(this,"finished",!1);I(this,"destroyed",!1);if(rs(e),z(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Pe(n)}update(e){return ke(this),this.iHash.update(e),this}digestInto(e){ke(this),z(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Is=(r,e,s)=>new Es(r,e).update(s).digest();Is.create=(r,e)=>new Es(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kt=(r,e)=>(r+(r>=0?e:-e)/As)/e;function Kr(r,e,s){const[[t,n],[o,i]]=e,a=Kt(i*r,s),c=Kt(-n*r,s);let l=r-a*t-c*o,u=-a*n-c*i;const h=l<_e,g=u<_e;h&&(l=-l),g&&(u=-u);const f=xt(Math.ceil(Rr(s)/2))+Re;if(l<_e||l>=f||u<_e||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:g,k2:u}}function lt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function nt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Ke(s.lowS,"lowS"),Ke(s.prehash,"prehash"),s.format!==void 0&<(s.format),s}class Vr extends Error{constructor(e=""){super(e)}}const ye={Err:Vr,_tlv:{encode:(r,e)=>{const{Err:s}=ye;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=Ue(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?Ue(n.length/2|128):"";return Ue(r)+o+n+e},decode(r,e){const{Err:s}=ye;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)i=i<<8|u;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ye;if(r<_e)throw new e("integer: negative integers are not allowed");let s=Ue(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=ye;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return je(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ye,n=z(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ye,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},_e=BigInt(0),Re=BigInt(1),As=BigInt(2),He=BigInt(3),zr=BigInt(4);function jr(r,e={}){const s=Wr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;gt(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=Rs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(A,_,x){const{x:b,y:E}=_.toAffine(),M=t.toBytes(b);if(Ke(x,"isCompressed"),x){u();const N=!t.isOdd(E);return ve(Ts(N),M)}else return ve(Uint8Array.of(4),M,t.toBytes(E))}function g(A){z(A,void 0,"Point");const{publicKey:_,publicKeyUncompressed:x}=l,b=A.length,E=A[0],M=A.subarray(1);if(b===_&&(E===2||E===3)){const N=t.fromBytes(M);if(!t.isValid(N))throw new Error("bad point: is not on curve, wrong x");const $=v(N);let T;try{T=t.sqrt($)}catch(J){const K=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}u();const B=t.isOdd(T);return(E&1)===1!==B&&(T=t.neg(T)),{x:N,y:T}}else if(b===x&&E===4){const N=t.BYTES,$=t.fromBytes(M.subarray(0,N)),T=t.fromBytes(M.subarray(N,N*2));if(!y($,T))throw new Error("bad point: is not on curve");return{x:$,y:T}}else throw new Error(`bad point: got length ${b}, expected compressed=${_} or uncompressed=${x}`)}const f=e.toBytes||h,w=e.fromBytes||g;function v(A){const _=t.sqr(A),x=t.mul(_,A);return t.add(t.add(x,t.mul(A,o.a)),o.b)}function y(A,_){const x=t.sqr(_),b=v(A);return t.eql(x,b)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const S=t.mul(t.pow(o.a,He),zr),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(A,_,x=!1){if(!t.isValid(_)||x&&t.is0(_))throw new Error(`bad point coordinate ${A}`);return _}function O(A){if(!(A instanceof D))throw new Error("Weierstrass Point expected")}function V(A){if(!c||!c.basises)throw new Error("no endo");return Kr(A,c.basises,n.ORDER)}const W=Bt((A,_)=>{const{X:x,Y:b,Z:E}=A;if(t.eql(E,t.ONE))return{x,y:b};const M=A.is0();_==null&&(_=M?t.ONE:t.inv(E));const N=t.mul(x,_),$=t.mul(b,_),T=t.mul(E,_);if(M)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:N,y:$}}),P=Bt(A=>{if(A.is0()){if(e.allowInfinityPoint&&!t.is0(A.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:x}=A.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(!A.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function k(A,_,x,b,E){return x=new D(t.mul(x.X,A),x.Y,x.Z),_=Ve(b,_),x=Ve(E,x),_.add(x)}const R=class R{constructor(_,x,b){I(this,"X");I(this,"Y");I(this,"Z");this.X=U("x",_),this.Y=U("y",x,!0),this.Z=U("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){const{x,y:b}=_||{};if(!_||!t.isValid(x)||!t.isValid(b))throw new Error("invalid affine point");if(_ instanceof R)throw new Error("projective point not allowed");return t.is0(x)&&t.is0(b)?R.ZERO:new R(x,b,t.ONE)}static fromBytes(_){const x=R.fromAffine(w(z(_,void 0,"point")));return x.assertValidity(),x}static fromHex(_){return R.fromBytes(qe(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,x=!0){return L.createCache(this,_),x||this.multiply(He),this}assertValidity(){P(this)}hasEvenY(){const{y:_}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(_)}equals(_){O(_);const{X:x,Y:b,Z:E}=this,{X:M,Y:N,Z:$}=_,T=t.eql(t.mul(x,$),t.mul(M,E)),B=t.eql(t.mul(b,$),t.mul(N,E));return T&&B}negate(){return new R(this.X,t.neg(this.Y),this.Z)}double(){const{a:_,b:x}=o,b=t.mul(x,He),{X:E,Y:M,Z:N}=this;let $=t.ZERO,T=t.ZERO,B=t.ZERO,G=t.mul(E,E),J=t.mul(M,M),K=t.mul(N,N),F=t.mul(E,M);return F=t.add(F,F),B=t.mul(E,N),B=t.add(B,B),$=t.mul(_,B),T=t.mul(b,K),T=t.add($,T),$=t.sub(J,T),T=t.add(J,T),T=t.mul($,T),$=t.mul(F,$),B=t.mul(b,B),K=t.mul(_,K),F=t.sub(G,K),F=t.mul(_,F),F=t.add(F,B),B=t.add(G,G),G=t.add(B,G),G=t.add(G,K),G=t.mul(G,F),T=t.add(T,G),K=t.mul(M,N),K=t.add(K,K),G=t.mul(K,F),$=t.sub($,G),B=t.mul(K,J),B=t.add(B,B),B=t.add(B,B),new R($,T,B)}add(_){O(_);const{X:x,Y:b,Z:E}=this,{X:M,Y:N,Z:$}=_;let T=t.ZERO,B=t.ZERO,G=t.ZERO;const J=o.a,K=t.mul(o.b,He);let F=t.mul(x,M),X=t.mul(b,N),Z=t.mul(E,$),oe=t.add(x,b),j=t.add(M,N);oe=t.mul(oe,j),j=t.add(F,X),oe=t.sub(oe,j),j=t.add(x,E);let Q=t.add(M,$);return j=t.mul(j,Q),Q=t.add(F,Z),j=t.sub(j,Q),Q=t.add(b,E),T=t.add(N,$),Q=t.mul(Q,T),T=t.add(X,Z),Q=t.sub(Q,T),G=t.mul(J,j),T=t.mul(K,Z),G=t.add(T,G),T=t.sub(X,G),G=t.add(X,G),B=t.mul(T,G),X=t.add(F,F),X=t.add(X,F),Z=t.mul(J,Z),j=t.mul(K,j),X=t.add(X,Z),Z=t.sub(F,Z),Z=t.mul(J,Z),j=t.add(j,Z),F=t.mul(X,j),B=t.add(B,F),F=t.mul(Q,j),T=t.mul(oe,T),T=t.sub(T,F),F=t.mul(oe,X),G=t.mul(Q,G),G=t.add(G,F),new R(T,B,G)}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 b,E;const M=N=>L.cached(this,N,$=>Ft(R,$));if(x){const{k1neg:N,k1:$,k2neg:T,k2:B}=V(_),{p:G,f:J}=M($),{p:K,f:F}=M(B);E=J.add(F),b=k(x.beta,G,K,N,T)}else{const{p:N,f:$}=M(_);b=N,E=$}return Ft(R,[b,E])[0]}multiplyUnsafe(_){const{endo:x}=e,b=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===_e||b.is0())return R.ZERO;if(_===Re)return b;if(L.hasCache(this))return this.multiply(_);if(x){const{k1neg:E,k1:M,k2neg:N,k2:$}=V(_),{p1:T,p2:B}=Gr(R,b,M,$);return k(x.beta,T,B,E,N)}else return L.unsafe(b,_)}toAffine(_){return W(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return i===Re?!0:_?_(R,this):L.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return i===Re?this:_?_(R,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(_=!0){return Ke(_,"isCompressed"),this.assertValidity(),f(R,this,_)}toHex(_=!0){return Me(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 D=R;const q=n.BITS,L=new Fr(D,e.endo?Math.ceil(q/2):q);return D.BASE.precompute(8),D}function Ts(r){return Uint8Array.of(r?2:3)}function Rs(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yr(r,e={}){const{Fn:s}=r,t=e.randomBytes||as,n=Object.assign(Rs(r.Fp,s),{seed:bs(s.ORDER)});function o(f){try{const w=s.fromBytes(f);return s.isValidNot0(w)}catch{return!1}}function i(f,w){const{publicKey:v,publicKeyUncompressed:y}=n;try{const S=f.length;return w===!0&&S!==v||w===!1&&S!==y?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return Hr(z(f,n.seed,"seed"),s.ORDER)}function c(f,w=!0){return r.BASE.multiply(s.fromBytes(f)).toBytes(w)}function l(f){const{secretKey:w,publicKey:v,publicKeyUncompressed:y}=n;if(!pt(f)||"_lengths"in s&&s._lengths||w===v)return;const S=z(f,void 0,"key").length;return S===v||S===y}function u(f,w,v=!0){if(l(f)===!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(f);return r.fromBytes(w).multiply(y).toBytes(v)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},g=qr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:g,Point:r,utils:h,lengths:n})}function Jr(r,e,s={}){rs(e),gt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||as,n=s.hmac||((_,x)=>Is(e,_,x)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:g,lengths:f}=Yr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},v=a*As<o.ORDER;function y(_){const x=a>>Re;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(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(_,x){lt(x);const b=f.signature,E=x==="compact"?b:x==="recovered"?b+1:void 0;return z(_,E)}class O{constructor(x,b,E){I(this,"r");I(this,"s");I(this,"recovery");if(this.r=S("r",x),this.s=S("s",b),E!=null){if(C(),![0,1,2,3].includes(E))throw new Error("invalid recovery id");this.recovery=E}Object.freeze(this)}static fromBytes(x,b=w.format){U(x,b);let E;if(b==="der"){const{r:T,s:B}=ye.toSig(z(x));return new O(T,B)}b==="recovered"&&(E=x[0],b="compact",x=x.subarray(1));const M=f.signature/2,N=x.subarray(0,M),$=x.subarray(M,M*2);return new O(i.fromBytes(N),i.fromBytes($),E)}static fromHex(x,b){return this.fromBytes(qe(x),b)}assertRecovery(){const{recovery:x}=this;if(x==null)throw new Error("invalid recovery id: must be present");return x}addRecoveryBit(x){return new O(this.r,this.s,x)}recoverPublicKey(x){const{r:b,s:E}=this,M=this.assertRecovery(),N=M===2||M===3?b+a:b;if(!o.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const $=o.toBytes(N),T=r.fromBytes(ve(Ts((M&1)===0),$)),B=i.inv(N),G=W(z(x,void 0,"msgHash")),J=i.create(-G*B),K=i.create(E*B),F=r.BASE.multiplyUnsafe(J).add(T.multiplyUnsafe(K));if(F.is0())throw new Error("invalid recovery: point at infinify");return F.assertValidity(),F}hasHighS(){return y(this.s)}toBytes(x=w.format){if(lt(x),x==="der")return qe(ye.hexFromSig(this));const{r:b,s:E}=this,M=i.toBytes(b),N=i.toBytes(E);return x==="recovered"?(C(),ve(Uint8Array.of(this.assertRecovery()),M,N)):ve(M,N)}toHex(x){return Me(this.toBytes(x))}}const V=s.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");const b=je(x),E=x.length*8-c;return E>0?b>>BigInt(E):b},W=s.bits2int_modN||function(x){return i.create(V(x))},P=xt(c);function k(_){return Tr("num < 2^"+c,_,_e,P),i.toBytes(_)}function D(_,x){return z(_,void 0,"message"),x?z(e(_),void 0,"prehashed message"):_}function q(_,x,b){const{lowS:E,prehash:M,extraEntropy:N}=nt(b,w);_=D(_,M);const $=W(_),T=i.fromBytes(x);if(!i.isValidNot0(T))throw new Error("invalid private key");const B=[k(T),k($)];if(N!=null&&N!==!1){const F=N===!0?t(f.secretKey):N;B.push(z(F,void 0,"extraEntropy"))}const G=ve(...B),J=$;function K(F){const X=V(F);if(!i.isValidNot0(X))return;const Z=i.inv(X),oe=r.BASE.multiply(X).toAffine(),j=i.create(oe.x);if(j===_e)return;const Q=i.create(Z*i.create(J+j*T));if(Q===_e)return;let vt=(oe.x===j?0:2)|Number(oe.y&Re),St=Q;return E&&y(Q)&&(St=i.neg(Q),vt^=1),new O(j,St,v?void 0:vt)}return{seed:G,k2sig:K}}function L(_,x,b={}){const{seed:E,k2sig:M}=q(_,x,b);return kr(e.outputLen,i.BYTES,n)(E,M).toBytes(b.format)}function R(_,x,b,E={}){const{lowS:M,prehash:N,format:$}=nt(E,w);if(b=z(b,void 0,"publicKey"),x=D(x,N),!pt(_)){const T=_ instanceof O?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}U(_,$);try{const T=O.fromBytes(_,$),B=r.fromBytes(b);if(M&&T.hasHighS())return!1;const{r:G,s:J}=T,K=W(x),F=i.inv(J),X=i.create(K*F),Z=i.create(G*F),oe=r.BASE.multiplyUnsafe(X).add(B.multiplyUnsafe(Z));return oe.is0()?!1:i.create(oe.x)===G}catch{return!1}}function A(_,x,b={}){const{prehash:E}=nt(b,w);return x=D(x,E),O.fromBytes(_,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:g,lengths:f,Point:r,sign:L,verify:R,recoverPublicKey:A,Signature:O,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Xr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Vt=BigInt(2);function Zr(r){const e=wt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=ae(u,s,e)*u%e,g=ae(h,s,e)*u%e,f=ae(g,Vt,e)*l%e,w=ae(f,n,e)*f%e,v=ae(w,o,e)*w%e,y=ae(v,a,e)*v%e,S=ae(y,c,e)*y%e,C=ae(S,a,e)*v%e,U=ae(C,s,e)*u%e,O=ae(U,i,e)*w%e,V=ae(O,t,e)*l%e,W=ae(V,Vt,e);if(!dt.eql(dt.sqr(W),r))throw new Error("Cannot find square root");return W}const dt=Ye(wt.p,{sqrt:Zr}),Qr=jr(wt,{Fp:dt,endo:Xr}),en=Jr(Qr,Er),tn=BigInt(0),Ne=BigInt(1),sn=BigInt(2),rn=BigInt(7),nn=BigInt(256),on=BigInt(113),ks=[],Ps=[],Os=[];for(let r=0,e=Ne,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ks.push(2*(5*t+s)),Ps.push((r+1)*(r+2)/2%64);let n=tn;for(let o=0;o<7;o++)e=(e<<Ne^(e>>rn)*on)%nn,e&sn&&(n^=Ne<<(Ne<<BigInt(o))-Ne);Os.push(n)}const Ns=xr(Os,!0),an=Ns[0],cn=Ns[1],zt=(r,e,s)=>s>32?wr(r,e,s):gr(r,e,s),jt=(r,e,s)=>s>32?yr(r,e,s):mr(r,e,s);function ln(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],u=s[c+1],h=zt(l,u,1)^s[a],g=jt(l,u,1)^s[a+1];for(let f=0;f<50;f+=10)r[i+f]^=h,r[i+f+1]^=g}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Ps[i],c=zt(n,o,a),l=jt(n,o,a),u=ks[i];n=r[u],o=r[u+1],r[u]=c,r[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=an[t],r[1]^=cn[t]}Pe(s)}class yt{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,ge(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ir(this.state)}clone(){return this._cloneInto()}keccak(){Dt(this.state32),ln(this.state32,this.rounds),Dt(this.state32),this.posOut=0,this.pos=0}update(e){ke(this),z(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){ke(this,!1),z(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ge(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ns(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 yt(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 dn=(r,e,s,t={})=>is(()=>new yt(e,r,s),t),Yt=dn(1,136,32),un=60;class hn{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Xe.createRemoteJWKSet(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+un<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:o}=await Xe.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Xe.decodeJwt(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=Yt(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=pn(a),l=c.slice(0,32),u=c.slice(32,64),h=c[64],g=h>=27?h-27:h,v=new en.Signature(Jt(l),Jt(u)).addRecoveryBit(g).recoverPublicKey(i).toBytes(!1).slice(1),y=Yt(v);return"0x"+Me(y.slice(12))}}function pn(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 Jt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const fn=3e4,_n=1e3;class xn{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,_n*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??fn);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const gn=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class be{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=be.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n==="")throw d.error("[CROSSx] nonce claim 누락 — JWT payload 전체 키 목록:",Object.keys(t)),d.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 be.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=be.generateRandom16Hex(),l=be.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const f=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),O(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,v=30;let y=0,S=null;const C=()=>{clearInterval(U),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),S=setTimeout(()=>{O(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},U=setInterval(()=>{y++;try{g.closed&&(y<=w?C():(O(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),O=()=>{clearTimeout(f),clearInterval(U),S&&clearTimeout(S),window.removeEventListener("message",V)},V=W=>{var k,D,q,L,R;if(W.origin!==e.expectedOrigin)return;if(!gn.has(W.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",W.origin),O(),t(new Error("Unauthorized OAuth origin"));return}O(),d.log("[CROSSx] OAuth postMessage 수신 — status:",W.data.status);const P=W.data.state??((k=W.data.data)==null?void 0:k.state);if(!P||P!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(W.data.status==="success"){const A=(D=W.data.data)==null?void 0:D.idToken,_=(q=W.data.data)==null?void 0:q.accessToken,x=_??A;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!_,hasIdToken:!!A}),!x){d.error("[CROSSx] 토큰을 찾을 수 없음:",W.data),t(new Error("Token not found in response"));return}A?be.verifyIdTokenNonce(A,l).then(()=>s(x)).catch(b=>{d.error("[CROSSx] nonce 검증 실패:",b),t(b instanceof Error?b:new Error("nonce verification failed"))}):_?_.split(".").length===3?be.verifyIdTokenNonce(_,l).then(()=>s(x)).catch(E=>{d.error("[CROSSx] accessToken nonce 검증 실패:",E),t(E instanceof Error?E:new Error("nonce verification failed"))}):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(x)):t(new Error("Token not found in response"))}else d.error("[CROSSx] OAuth 실패:",(L=W.data.data)==null?void 0:L.error),t(new Error(((R=W.data.data)==null?void 0:R.error)||"Authentication failed"))};window.addEventListener("message",V)})}}const Ce="crossx_wallet_data",Te="crossx_mock_pin_hash";class mn{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Ce)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Ce);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(Ce,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Te,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new m(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Ce);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Te);return s&&s!==e?!1:(s||await this.storage.set(Te,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new m(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Te);if(n&&t&&n!==t)throw new m(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Te,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new m(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new m(p.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Ce,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Te,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Le{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 m(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 u=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(u&&typeof u.code=="number"){if(u.code<0||u.code>=400){const h=u.message||u.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:u.code,message:h,url:o,method:e});const g=Le.mapGatewayError(u.code,u.data),f=Le.getGatewayErrorMessage(u.code,h),w=u.data,v=g===p.PIN_LOCKED?Le.extractLockDetails(w):w??void 0,y=new m(g,f,v);throw g===p.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(d.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:u.code,url:o,method:e}),u.data??u}return u}catch(l){if(l instanceof m)throw l;if((a=l.response)!=null&&a.data){const u=l.response.data,h=u.message||u.data||"API 요청에 실패했습니다",g=u.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:g,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new m(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${g}): ${h}`)}throw l}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new m(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new m(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new m(p.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new m(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e};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 m(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:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10007:return p.BROADCAST_FAILED;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10004:return p.WALLET_ALREADY_EXISTS;case-10005:return p.WALLET_NOT_FOUND;case-10011:return p.WALLET_NOT_FOUND;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10013:return p.WITHDRAW_FAILED;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10025:return p.INVALID_APP_TYPE;case-10028:return p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10032:return p.PIN_REPEATED_PATTERN;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10040:return p.HMAC_REQUIRED;case-10041:return p.HMAC_VERIFICATION_FAILED;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class De{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=De.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(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?sr:tr;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new m(De.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=De.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new m(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(ze).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 Xt="__crossx-confirm-style",te="__crossx-confirm-overlay",wn={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 Zt(r,e){const s=wn[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 yn=`
|
|
1
|
+
"use strict";var $s=Object.defineProperty;var Bs=(r,e,s)=>e in r?$s(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var E=(r,e,s)=>Bs(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Xe=require("jose");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.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",r.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.BROADCAST_FAILED="BROADCAST_FAILED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",r.PIN_CANCELLED="PIN_CANCELLED",r.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",r.PIN_LOCKED="PIN_LOCKED",r.HMAC_REQUIRED="HMAC_REQUIRED",r.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",r.WITHDRAW_FAILED="WITHDRAW_FAILED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class m extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const 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}},Us=Object.fromEntries(Object.entries(ze).map(([r,e])=>[r,e.caipId])),Hs=new Map(Object.values(ze).map(r=>[r.caipId,r]));new Map(Object.values(ze).map(r=>[r.chainId,r]));const Fs={symbol:"",decimals:18};function Ze(r){var e;return((e=Hs.get(r))==null?void 0:e.nativeCurrency)??Fs}class ts{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new m(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,s,this.chainId)}}on(e,s){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(s),this}removeListener(e,s){var t;return(t=this._listeners.get(e))==null||t.delete(s),this}emit(e,...s){var t;(t=this._listeners.get(e))==null||t.forEach(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 Et(r){Se=r}const d={log(...r){if(Se){Se.log(...r);return}},warn(...r){if(Se){Se.warn(...r);return}},error(...r){if(Se){Se.error(...r);return}}},Gs={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간"},ss={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from"},Ws={ko:Gs,en:ss};function It(r="en",e){return Ws[r]??ss}const At="crossx_access_token",Tt="crossx_refresh_token",Rt="crossx_user_info";class qs{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new m(p.AUTH_FAILED,`${s} 실패 (코드 ${e.code}): ${e.message}`);const t=e==null?void 0:e.data;if(typeof t=="object"&&t!==null&&"code"in t){const n=t;if(n.code&&n.code!==200&&n.code>0)throw new m(p.AUTH_FAILED,`${s} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){let s;try{const t=e==null?void 0:e.provider;let n="/login";t==="google"?n="/google":t==="apple"&&(n="/apple");const{oauthServiceUrl:o}=this.config,i=`${o}${n}`;d.log(`[CROSSx] OAuth 팝업 열기 (${t||"일반"} 로그인)`),s=await this.oauth.openAuth({authUrl:i,expectedOrigin:new URL(o).origin}),d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",s.length,")")}catch(t){return d.error("[CROSSx] SignIn 에러 (OAuth 단계):",t),{success:!1,error:t instanceof Error?t.message:"Sign in failed"}}return this.processFirebaseToken(s)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e){var n,o,i,a;let s,t=!1;try{const{authApiUrl:c}=this.config,{accessToken:l,refreshToken:u}=await this.exchangeFirebaseToken(e,c);let h,x;try{const w=this.crypto.decodeJWT(e);x=(n=w.firebase)==null?void 0:n.sign_in_provider;const b=((o=w.firebase)==null?void 0:o.identities)??{};x==="google.com"?h=(i=b["google.com"])==null?void 0:i[0]:x==="apple.com"&&(h=(a=b["apple.com"])==null?void 0:a[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",x,"hasProviderSub:",!!h)}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(l){const w=this.crypto.decodeJWT(l);d.log("[CROSSx] access_token 디코딩 — sub:",w.sub,"exp:",w.exp);const b=await this.crypto.verifyJWT(l);if(t=b.signatureVerified??!1,!b.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const y=b.payload;s={id:y.sub,email:y.email,signInProvider:x,providerSub:h},this.tokenStore.set(l),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l),u&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u):u&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const w=this.crypto.decodeJWT(e);s={id:w.sub,email:w.email,signInProvider:x,providerSub:h},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}d.log("[CROSSx] 사용자 정보 — id:",s.id);const f=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(this.STORAGE_KEY_USER,f),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",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`;d.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new m(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return d.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl: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"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new m(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,c);const l=this.extractRefreshToken(a);l&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,l)}return d.log("[CROSSx] silentRefresh 성공"),c}async executeWithJWT(e,s){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!s)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;d.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),s&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,s)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return d.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(Rt);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(At);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(Tt);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(Rt),await this.storage.remove(At),await this.storage.remove(Tt),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",o),o==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof m&&o.code===p.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof m&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}class Ks{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class Vs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new m(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class ht{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const s=new TextEncoder().encode(e),t=new Uint8Array(s.length);crypto.getRandomValues(t);const n=new Uint8Array(s.length);for(let o=0;o<s.length;o++)n[o]=s[o]^t[o];s.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const s=new TextDecoder().decode(e);return e.fill(0),s}clear(){var e,s;(e=this.encryptedBytes)==null||e.fill(0),(s=this.xorKey)==null||s.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class zs{constructor(e,s){this.chainRegistry=e,this.transport=s,this._nextId=1}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new m(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 Ge={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 Ge?Ge[e]:null}function Js(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=Ys(r);if(e)return e}}catch{}return Ge.production}const Xs=2e3,kt=6e4,Zs=1e3,Qs=1e4,er="0x77359400",Pt="0x3B9ACA00",Ot=130,Ct=6,Nt=18,tr=5*60*1e3,sr=30*1e3,re=class re extends js{constructor(e,s,t,n,o,i,a,c,l,u,h){var x;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&Et(e.logger),this.confirmation=l,this.pinStore=h??new ht,this.chainRegistry=u,this.jsonRpc=new zs(u,o),this.signInUseCase=new qs(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Ks(this.internalConfig,t,c),this.migrateWalletUseCase=new Vs(t,a),(x=a.setOnUnauthorized)==null||x.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 s,t;d.log("[CROSSx SDK] v1.3.6 초기화 중..."),this.confirmation.setMessages(It(this._config.locale));try{const n=Js();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(s=this.crypto).setJWKSEndpoint)==null||t.call(s,`${n.authApiUrl}/.well-known/jwks.json`);const o=await this.signInUseCase.restoreSession();if(o!=null&&o.success){this.applyAuthResult(o);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(i){if(!(i instanceof m&&i.code===p.PIN_CANCELLED))throw i;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(o!=null&&o.success)}),o??null}catch(n){throw new m(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new m(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new m(p.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(p.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const s=await this.signIn(e);if(!s.success)return{...s,addresses:[]};try{if(s.needsMigration||!s.address){const{address: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 m&&t.code===p.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new m(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const s=await this.signInUseCase.executeWithOAuthToken(e);return s.success&&this.applyAuthResult(s),s}catch(s){throw new m(p.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",s)}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new m(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new m(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof m&&s.code===p.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof m?s:new m(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.walletProvider.getAddresses(this.userId);return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(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 m?e:new m(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof m?s:new m(p.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,s)}}applyTheme(e=this._config.theme??"light",s=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:s}),this.confirmation.setTheme(e,s)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(It(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new m(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(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 m(p.USER_REJECTED,"User rejected the message signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof m?i:new m(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new m(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");re.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 m(p.USER_REJECTED,"User rejected the typed data signing request");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return re.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof m?i:new m(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,i)}}async signTypedDataOffchain(e,s){return this.signTypedData(re.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(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=Ze(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return re.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(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=Ze(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new m(p.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof m)throw a;const c=a instanceof Error?a.message:String(a);throw new m(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??Zs,o=Qs,i=t.timeoutMs??kt,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,o)}throw new m(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Xs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??kt,u=Ze(e),h=s.from??"";let x,f;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(k=>{x=k;const N=BigInt(k.gasUsed)*BigInt(k.effectiveGasPrice),W=s.value?BigInt(s.value):0n,B=re.formatTxAmount(s.value,u.symbol,u.decimals),j=re.formatTxAmount("0x"+N.toString(16),u.symbol,u.decimals),q=re.formatTxAmount("0x"+(W+N).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:k.from,to:k.to??s.to,amount:B,fees:j,total:q,nativeSymbol:u.symbol,status:k.status==="0x1"?"success":"reverted"}}).catch(k=>(f=k instanceof Error?k:new Error(String(k)),{chainId:e,txHash:a,from:h,to:s.to,amount:re.formatTxAmount(s.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:s.to},w),f)throw f;return{chainId:e,txHash:a,receipt:x}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new m(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof m?n:new m(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 m(p.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,s)}}async estimateGas(e,s){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],s)}catch(n){const o=n instanceof Error?n.message:String(n);throw new m(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 m(p.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(p.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof m)throw t;const n=t instanceof Error?t.message:String(t);throw new m(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:re.formatWei(n),chainId:e}}catch(t){if(t instanceof m)throw t;const n=t instanceof Error?t.message:String(t);throw new m(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(Nt),n=s/t,i=(s%t).toString().padStart(Nt,"0").replace(/0+$/,"").slice(0,Ct);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new ts(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof m)throw n;const o=n instanceof Error?n.message:String(n);throw new m(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,Ct).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:s});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,o=0,i=5,a=null;for(;;){o++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${i})`,n?`— 이전 메시지: ${n}`:"");const h=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:o>1?o-1:void 0,maxAttempts:i});if(h===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const x=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,h,e));if(!x){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=h;break}if(x.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=h;break}const f=x.pinStatus;if(i=f.maxAttempts,o=i-f.remainingAttempts,f.remainingAttempts===0&&f.lockExpiresAt){const w=f.lockExpiresAt*1e3,b=Math.max(1,Math.round((w-Date.now())/1e3)),y=b<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${b}초, 메시지: ${y}`),await this.confirmation.showRecoveryPinLockedPrompt(b,y),o=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${i})`),n="Incorrect PIN."}catch(x){if(!(x instanceof m))throw x;if(x.code===p.MIGRATION_PIN_LOCKED){const f=x.details;if(i=(f==null?void 0:f.maxAttempts)??5,(f==null?void 0:f.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((f==null?void 0:f.lockExpiresAt)??0)*1e3,b=Math.max(1,Math.round((w-Date.now())/1e3)),y=b<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${b}초`),await this.confirmation.showRecoveryPinLockedPrompt(b,y),o=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",x),x}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const h=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",h.address),h}catch(h){if(h instanceof m&&h.code===p.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",h),h}}async withResolvedGasAndFee(e,s){const t=f=>!(f!=null&&f.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),o&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),i&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,h,x]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s):null,o?this.estimateGas(e,s):null,i?this.getBaseFeePerGas(s):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),o&&(c.gasLimit=h,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){const f=x;if(f){const w=Pt;c.maxFeePerGas="0x"+(BigInt(f)+BigInt(w)).toString(16),c.maxPriorityFeePerGas=w,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",f,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=er,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Pt,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=re.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const o=Number(n[1]);if(t===void 0)throw new m(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new m(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 m(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Ot)throw new m(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Ot} hex 문자(65 바이트) 예상, 현재 ${s.length}`)}static validateSignedTxFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new m(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new m(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new m(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof m)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var 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=re.normalizeLoginType((o=e.user)==null?void 0:o.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new m(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new m(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s});if(!i)throw new m(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}const o=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof m){if(c.code===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 m(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(o),d.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(d.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,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let s,t;try{return await e()}catch(n){if(n instanceof m)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(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",s),this.pinStore.clear(),await this.ensureVerifiedPin(s,t),t=void 0;try{return await e()}catch(n){if(n instanceof m){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 m(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 m(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),Et(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};re.OFFCHAIN_CHAIN_ID="0";let We=re;class rr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return d.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw d.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Qe="crossx-sdk",nr=1,de="data",ve="keys",$e="aes-primary",or=12;class Lt{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((s,t)=>{const n=indexedDB.open(e,nr);n.onupgradeneeded=()=>{const o=n.result;o.objectStoreNames.contains(de)||o.createObjectStore(de),o.objectStoreNames.contains(ve)||o.createObjectStore(ve)},n.onsuccess=()=>s(n.result),n.onerror=()=>t(n.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(ve,$e);if(e){this.cryptoKey=e;return}const s=await this.migrateFromLegacyDB();if(s){this.cryptoKey=s;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(ve,$e,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Qe)return null;try{const e=await this.openDB(Qe),s=e.transaction([ve,de],"readonly"),t=s.objectStore(ve).get($e),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const o=s.objectStore(de).getAll(),i=s.objectStore(de).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)}),new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)})]);e.close(),await this.idbPut(ve,$e,n);for(let l=0;l<c.length;l++)await this.idbPut(de,String(c[l]),a[l]);return indexedDB.deleteDatabase(Qe),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const s=new Uint8Array(or);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(de,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(de,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return d.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(de,e)}catch(s){throw d.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(de)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function ge(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function V(r,e,s=""){const t=pt(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 rs(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");ge(r.outputLen),ge(r.blockLen)}function ke(r,e=!0){if(r.destroyed)throw new Error("Hash instance has been destroyed");if(e&&r.finished)throw new Error("Hash#digest() has already been called")}function ns(r,e){V(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function ir(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 et(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ue(r,e){return r<<32-e|r>>>e}const ar=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function lr(r){for(let e=0;e<r.length;e++)r[e]=cr(r[e]);return r}const Dt=ar?r=>r:lr,os=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Me(r){if(V(r),os)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=dr[r[s]];return e}const fe={_0:48,_9:57,A:65,F:70,a:97,f:102};function Mt(r){if(r>=fe._0&&r<=fe._9)return r-fe._0;if(r>=fe.A&&r<=fe.F)return r-(fe.A-10);if(r>=fe.a&&r<=fe.f)return r-(fe.a-10)}function qe(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(os)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=Mt(r.charCodeAt(o)),a=Mt(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 be(...r){let e=0;for(let t=0;t<r.length;t++){const n=r[t];V(n),e+=n.length}const s=new Uint8Array(e);for(let t=0,n=0;t<r.length;t++){const o=r[t];s.set(o,n),n+=o.length}return s}function is(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 as(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 ur=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function hr(r,e,s){return r&e^~r&s}function pr(r,e,s){return r&e^r&s^e&s}class fr{constructor(e,s,t,n){E(this,"blockLen");E(this,"outputLen");E(this,"padOffset");E(this,"isLE");E(this,"buffer");E(this,"view");E(this,"finished",!1);E(this,"length",0);E(this,"pos",0);E(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=et(this.buffer)}update(e){ke(this),V(e);const{view:s,buffer:t,blockLen:n}=this,o=e.length;for(let i=0;i<o;){const a=Math.min(n-this.pos,o-i);if(a===n){const c=et(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){ke(this),ns(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=et(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],o)}digest(){const{buffer:e,outputLen: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 me=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Be=BigInt(2**32-1),$t=BigInt(32);function _r(r,e=!1){return e?{h:Number(r&Be),l:Number(r>>$t&Be)}:{h:Number(r>>$t&Be)|0,l:Number(r&Be)|0}}function xr(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}=_r(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const gr=(r,e,s)=>r<<s|e>>>32-s,mr=(r,e,s)=>e<<s|r>>>32-s,wr=(r,e,s)=>e<<s-32|r>>>64-s,yr=(r,e,s)=>r<<s-32|e>>>64-s,br=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]),we=new Uint32Array(64);class vr extends fr{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)we[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const x=we[h-15],f=we[h-2],w=ue(x,7)^ue(x,18)^x>>>3,b=ue(f,17)^ue(f,19)^f>>>10;we[h]=b+we[h-7]+w+we[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const x=ue(a,6)^ue(a,11)^ue(a,25),f=u+x+hr(a,c,l)+br[h]+we[h]|0,b=(ue(t,2)^ue(t,13)^ue(t,22))+pr(t,n,o)|0;u=l,l=c,c=a,a=i+f|0,i=o,o=n,n=t,t=f+b|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,o,i,a,c,l,u)}roundClean(){Pe(we)}destroy(){this.set(0,0,0,0,0,0,0,0),Pe(this.buffer)}}class Sr extends vr{constructor(){super(32);E(this,"A",me[0]|0);E(this,"B",me[1]|0);E(this,"C",me[2]|0);E(this,"D",me[3]|0);E(this,"E",me[4]|0);E(this,"F",me[5]|0);E(this,"G",me[6]|0);E(this,"H",me[7]|0)}}const Er=is(()=>new Sr,ur(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ft=BigInt(0),ct=BigInt(1);function Ke(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function cs(r){if(typeof r=="bigint"){if(!Fe(r))throw new Error("positive bigint expected, got "+r)}else ge(r);return r}function Ue(r){const e=cs(r).toString(16);return e.length&1?"0"+e:e}function ls(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ft:BigInt("0x"+r)}function je(r){return ls(Me(r))}function ds(r){return ls(Me(Ir(V(r)).reverse()))}function _t(r,e){ge(e),r=cs(r);const s=qe(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function us(r,e){return _t(r,e).reverse()}function Ir(r){return Uint8Array.from(r)}const Fe=r=>typeof r=="bigint"&&ft<=r;function Ar(r,e,s){return Fe(r)&&Fe(e)&&Fe(s)&&e<=r&&r<s}function Tr(r,e,s,t){if(!Ar(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Rr(r){let e;for(e=0;r>ft;r>>=ct,e+=1);return e}const xt=r=>(ct<<BigInt(r))-ct;function kr(r,e,s){if(ge(r,"hashLen"),ge(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),u=0;const h=()=>{c.fill(1),l.fill(0),u=0},x=(...y)=>s(l,be(c,...y)),f=(y=n)=>{l=x(o,y),c=x(),y.length!==0&&(l=x(i,y),c=x())},w=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const k=[];for(;y<e;){c=x();const N=c.slice();k.push(N),y+=c.length}return be(...k)};return(y,k)=>{h(),f(y);let N;for(;!(N=k(w()));)f();return h(),N}}function gt(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 Bt(r){const e=new WeakMap;return(s,...t)=>{const n=e.get(s);if(n!==void 0)return n;const o=r(s,...t);return e.set(s,o),o}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ne=BigInt(0),ee=BigInt(1),Ie=BigInt(2),hs=BigInt(3),ps=BigInt(4),fs=BigInt(5),Pr=BigInt(7),_s=BigInt(8),Or=BigInt(9),xs=BigInt(16);function le(r,e){const s=r%e;return s>=ne?s:e+s}function ae(r,e,s){let t=r;for(;e-- >ne;)t*=t,t%=s;return t}function Ut(r,e){if(r===ne)throw new Error("invert: expected non-zero number");if(e<=ne)throw new Error("invert: expected positive modulus, got "+e);let s=le(r,e),t=e,n=ne,o=ee;for(;s!==ne;){const a=t/s,c=t%s,l=n-o*a;t=s,s=c,n=o,o=l}if(t!==ee)throw new Error("invert: does not exist");return le(n,e)}function mt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function gs(r,e){const s=(r.ORDER+ee)/ps,t=r.pow(e,s);return mt(r,t,e),t}function Cr(r,e){const s=(r.ORDER-fs)/_s,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 mt(r,a,e),a}function Nr(r){const e=Ye(r),s=ms(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Pr)/xs;return(a,c)=>{let l=a.pow(c,i),u=a.mul(l,t);const h=a.mul(l,n),x=a.mul(l,o),f=a.eql(a.sqr(u),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,u,f),u=a.cmov(x,h,w);const b=a.eql(a.sqr(u),c),y=a.cmov(l,u,b);return mt(a,y,c),y}}function ms(r){if(r<hs)throw new Error("sqrt is not defined for small field");let e=r-ee,s=0;for(;e%Ie===ne;)e/=Ie,s++;let t=Ie;const n=Ye(r);for(;Ht(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return gs;let o=n.pow(t,e);const i=(e+ee)/Ie;return function(c,l){if(c.is0(l))return l;if(Ht(c,l)!==1)throw new Error("Cannot find square root");let u=s,h=c.mul(c.ONE,o),x=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(x,c.ONE);){if(c.is0(x))return c.ZERO;let w=1,b=c.sqr(x);for(;!c.eql(b,c.ONE);)if(w++,b=c.sqr(b),w===u)throw new Error("Cannot find square root");const y=ee<<BigInt(u-w-1),k=c.pow(h,y);u=w,h=c.sqr(k),x=c.mul(x,h),f=c.mul(f,k)}return f}}function Lr(r){return r%ps===hs?gs:r%_s===fs?Cr:r%xs===Or?Nr(r):ms(r)}const Dr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Dr.reduce((t,n)=>(t[n]="function",t),e);return gt(r,s),r}function $r(r,e,s){if(s<ne)throw new Error("invalid exponent, negatives unsupported");if(s===ne)return r.ONE;if(s===ee)return e;let t=r.ONE,n=e;for(;s>ne;)s&ee&&(t=r.mul(t,n)),n=r.sqr(n),s>>=ee;return t}function ws(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 Ht(r,e){const s=(r.ORDER-ee)/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 Br(r,e){e!==void 0&&ge(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ur{constructor(e,s={}){E(this,"ORDER");E(this,"BITS");E(this,"BYTES");E(this,"isLE");E(this,"ZERO",ne);E(this,"ONE",ee);E(this,"_lengths");E(this,"_sqrt");E(this,"_mod");var i;if(e<=ne)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,s!=null&&typeof s=="object"&&(typeof s.BITS=="number"&&(t=s.BITS),typeof s.sqrt=="function"&&(this.sqrt=s.sqrt),typeof s.isLE=="boolean"&&(this.isLE=s.isLE),s.allowedLengths&&(this._lengths=(i=s.allowedLengths)==null?void 0:i.slice()),typeof s.modFromBytes=="boolean"&&(this._mod=s.modFromBytes));const{nBitLength:n,nByteLength:o}=Br(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 le(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ne<=e&&e<this.ORDER}is0(e){return e===ne}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ee)===ee}neg(e){return le(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return le(e*e,this.ORDER)}add(e,s){return le(e+s,this.ORDER)}sub(e,s){return le(e-s,this.ORDER)}mul(e,s){return le(e*s,this.ORDER)}pow(e,s){return $r(this,e,s)}div(e,s){return le(e*Ut(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 Ut(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Lr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?us(e,this.BYTES):_t(e,this.BYTES)}fromBytes(e,s=!1){V(e);const{_lengths:t,BYTES:n,isLE:o,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,o?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=o?ds(e):je(e);if(a&&(c=le(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ws(this,e)}cmov(e,s,t){return t?s:e}}function Ye(r,e={}){return new Ur(r,e)}function ys(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 bs(r){const e=ys(r);return e+Math.ceil(e/2)}function Hr(r,e,s=!1){V(r);const t=r.length,n=ys(e),o=bs(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?ds(r):je(r),a=le(i,e-ee)+ee;return s?us(a,n):_t(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oe=BigInt(0),Ae=BigInt(1);function Ve(r,e){const s=e.negate();return r?s:e}function Ft(r,e){const s=ws(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function vs(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tt(r,e){vs(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=xt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Gt(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+=Ae);const l=e*t,u=l+Math.abs(a)-1,h=a===0,x=a<0,f=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:x,isNegF:f,offsetF:l}}const st=new WeakMap,Ss=new WeakMap;function rt(r){return Ss.get(r)||1}function Wt(r){if(r!==Oe)throw new Error("invalid wNAF")}class Fr{constructor(e,s){E(this,"BASE");E(this,"ZERO");E(this,"Fn");E(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let n=e;for(;s>Oe;)s&Ae&&(t=t.add(n)),n=n.double(),s>>=Ae;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=tt(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=tt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:x,offsetF:f}=Gt(t,a,i);t=c,u?o=o.add(Ve(x,s[f])):n=n.add(Ve(h,s[l]))}return Wt(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=tt(e,this.bits);for(let i=0;i<o.windows&&t!==Oe;i++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Gt(t,i,o);if(t=a,!l){const h=s[c];n=n.add(u?h.negate():h)}}return Wt(t),n}getPrecomputes(e,s,t){let n=st.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),st.set(s,n))),n}cached(e,s,t){const n=rt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=rt(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){vs(s,this.bits),Ss.set(e,s),st.delete(e)}hasCache(e){return rt(e)!==1}}function Gr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Oe||t>Oe;)s&Ae&&(o=o.add(n)),t&Ae&&(i=i.add(n)),n=n.double(),s>>=Ae,t>>=Ae;return{p1:o,p2:i}}function qt(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Mr(e),e}else return Ye(r,{isLE:s})}function Wr(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>Oe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=qt(e.p,s.Fp,t),o=qt(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 qr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class Es{constructor(e,s){E(this,"oHash");E(this,"iHash");E(this,"blockLen");E(this,"outputLen");E(this,"finished",!1);E(this,"destroyed",!1);if(rs(e),V(s,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(s.length>t?e.create().update(s).digest():s);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),Pe(n)}update(e){return ke(this),this.iHash.update(e),this}digestInto(e){ke(this),V(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:s,iHash:t,finished:n,destroyed:o,blockLen:i,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=o,e.blockLen=i,e.outputLen=a,e.oHash=s._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Is=(r,e,s)=>new Es(r,e).update(s).digest();Is.create=(r,e)=>new Es(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kt=(r,e)=>(r+(r>=0?e:-e)/As)/e;function Kr(r,e,s){const[[t,n],[o,i]]=e,a=Kt(i*r,s),c=Kt(-n*r,s);let l=r-a*t-c*o,u=-a*n-c*i;const h=l<_e,x=u<_e;h&&(l=-l),x&&(u=-u);const f=xt(Math.ceil(Rr(s)/2))+Re;if(l<_e||l>=f||u<_e||u>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:x,k2:u}}function lt(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function nt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return Ke(s.lowS,"lowS"),Ke(s.prehash,"prehash"),s.format!==void 0&<(s.format),s}class Vr extends Error{constructor(e=""){super(e)}}const ye={Err:Vr,_tlv:{encode:(r,e)=>{const{Err:s}=ye;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length&1)throw new s("tlv.encode: unpadded data");const t=e.length/2,n=Ue(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?Ue(n.length/2|128):"";return Ue(r)+o+n+e},decode(r,e){const{Err:s}=ye;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const u of l)i=i<<8|u;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=ye;if(r<_e)throw new e("integer: negative integers are not allowed");let s=Ue(r);if(Number.parseInt(s[0],16)&8&&(s="00"+s),s.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return s},decode(r){const{Err:e}=ye;if(r[0]&128)throw new e("invalid signature integer: negative");if(r[0]===0&&!(r[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return je(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=ye,n=V(r,void 0,"signature"),{v:o,l:i}=t.decode(48,n);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,o),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=ye,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},_e=BigInt(0),Re=BigInt(1),As=BigInt(2),He=BigInt(3),zr=BigInt(4);function jr(r,e={}){const s=Wr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;gt(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=Rs(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(I,_,g){const{x:v,y:R}=_.toAffine(),D=t.toBytes(v);if(Ke(g,"isCompressed"),g){u();const C=!t.isOdd(R);return be(Ts(C),D)}else return be(Uint8Array.of(4),D,t.toBytes(R))}function x(I){V(I,void 0,"Point");const{publicKey:_,publicKeyUncompressed:g}=l,v=I.length,R=I[0],D=I.subarray(1);if(v===_&&(R===2||R===3)){const C=t.fromBytes(D);if(!t.isValid(C))throw new Error("bad point: is not on curve, wrong x");const M=b(C);let T;try{T=t.sqrt(M)}catch(J){const K=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}u();const $=t.isOdd(T);return(R&1)===1!==$&&(T=t.neg(T)),{x:C,y:T}}else if(v===g&&R===4){const C=t.BYTES,M=t.fromBytes(D.subarray(0,C)),T=t.fromBytes(D.subarray(C,C*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=${g}`)}const f=e.toBytes||h,w=e.fromBytes||x;function b(I){const _=t.sqr(I),g=t.mul(_,I);return t.add(t.add(g,t.mul(I,o.a)),o.b)}function y(I,_){const g=t.sqr(_),v=b(I);return t.eql(g,v)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const k=t.mul(t.pow(o.a,He),zr),N=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(k,N)))throw new Error("bad curve params: a or b");function W(I,_,g=!1){if(!t.isValid(_)||g&&t.is0(_))throw new Error(`bad point coordinate ${I}`);return _}function B(I){if(!(I instanceof L))throw new Error("Weierstrass Point expected")}function j(I){if(!c||!c.basises)throw new Error("no endo");return Kr(I,c.basises,n.ORDER)}const q=Bt((I,_)=>{const{X:g,Y:v,Z:R}=I;if(t.eql(R,t.ONE))return{x:g,y:v};const D=I.is0();_==null&&(_=D?t.ONE:t.inv(R));const C=t.mul(g,_),M=t.mul(v,_),T=t.mul(R,_);if(D)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:C,y:M}}),P=Bt(I=>{if(I.is0()){if(e.allowInfinityPoint&&!t.is0(I.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:g}=I.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(!I.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function S(I,_,g,v,R){return g=new L(t.mul(g.X,I),g.Y,g.Z),_=Ve(v,_),g=Ve(R,g),_.add(g)}const A=class A{constructor(_,g,v){E(this,"X");E(this,"Y");E(this,"Z");this.X=W("x",_),this.Y=W("y",g,!0),this.Z=W("z",v),Object.freeze(this)}static CURVE(){return o}static fromAffine(_){const{x:g,y:v}=_||{};if(!_||!t.isValid(g)||!t.isValid(v))throw new Error("invalid affine point");if(_ instanceof A)throw new Error("projective point not allowed");return t.is0(g)&&t.is0(v)?A.ZERO:new A(g,v,t.ONE)}static fromBytes(_){const g=A.fromAffine(w(V(_,void 0,"point")));return g.assertValidity(),g}static fromHex(_){return A.fromBytes(qe(_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,g=!0){return O.createCache(this,_),g||this.multiply(He),this}assertValidity(){P(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:v,Z:R}=this,{X:D,Y:C,Z:M}=_,T=t.eql(t.mul(g,M),t.mul(D,R)),$=t.eql(t.mul(v,M),t.mul(C,R));return T&&$}negate(){return new A(this.X,t.neg(this.Y),this.Z)}double(){const{a:_,b:g}=o,v=t.mul(g,He),{X:R,Y:D,Z:C}=this;let M=t.ZERO,T=t.ZERO,$=t.ZERO,F=t.mul(R,R),J=t.mul(D,D),K=t.mul(C,C),H=t.mul(R,D);return H=t.add(H,H),$=t.mul(R,C),$=t.add($,$),M=t.mul(_,$),T=t.mul(v,K),T=t.add(M,T),M=t.sub(J,T),T=t.add(J,T),T=t.mul(M,T),M=t.mul(H,M),$=t.mul(v,$),K=t.mul(_,K),H=t.sub(F,K),H=t.mul(_,H),H=t.add(H,$),$=t.add(F,F),F=t.add($,F),F=t.add(F,K),F=t.mul(F,H),T=t.add(T,F),K=t.mul(D,C),K=t.add(K,K),F=t.mul(K,H),M=t.sub(M,F),$=t.mul(K,J),$=t.add($,$),$=t.add($,$),new A(M,T,$)}add(_){B(_);const{X:g,Y:v,Z:R}=this,{X:D,Y:C,Z:M}=_;let T=t.ZERO,$=t.ZERO,F=t.ZERO;const J=o.a,K=t.mul(o.b,He);let H=t.mul(g,D),X=t.mul(v,C),Z=t.mul(R,M),oe=t.add(g,v),z=t.add(D,C);oe=t.mul(oe,z),z=t.add(H,X),oe=t.sub(oe,z),z=t.add(g,R);let Q=t.add(D,M);return z=t.mul(z,Q),Q=t.add(H,Z),z=t.sub(z,Q),Q=t.add(v,R),T=t.add(C,M),Q=t.mul(Q,T),T=t.add(X,Z),Q=t.sub(Q,T),F=t.mul(J,z),T=t.mul(K,Z),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),Z=t.mul(J,Z),z=t.mul(K,z),X=t.add(X,Z),Z=t.sub(H,Z),Z=t.mul(J,Z),z=t.add(z,Z),H=t.mul(X,z),$=t.add($,H),H=t.mul(Q,z),T=t.mul(oe,T),T=t.sub(T,H),H=t.mul(oe,X),F=t.mul(Q,F),F=t.add(F,H),new A(T,$,F)}subtract(_){return this.add(_.negate())}is0(){return this.equals(A.ZERO)}multiply(_){const{endo:g}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let v,R;const D=C=>O.cached(this,C,M=>Ft(A,M));if(g){const{k1neg:C,k1:M,k2neg:T,k2:$}=j(_),{p:F,f:J}=D(M),{p:K,f:H}=D($);R=J.add(H),v=S(g.beta,F,K,C,T)}else{const{p:C,f:M}=D(_);v=C,R=M}return Ft(A,[v,R])[0]}multiplyUnsafe(_){const{endo:g}=e,v=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===_e||v.is0())return A.ZERO;if(_===Re)return v;if(O.hasCache(this))return this.multiply(_);if(g){const{k1neg:R,k1:D,k2neg:C,k2:M}=j(_),{p1:T,p2:$}=Gr(A,v,D,M);return S(g.beta,T,$,R,C)}else return O.unsafe(v,_)}toAffine(_){return q(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return i===Re?!0:_?_(A,this):O.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return i===Re?this:_?_(A,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(_=!0){return Ke(_,"isCompressed"),this.assertValidity(),f(A,this,_)}toHex(_=!0){return Me(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};E(A,"BASE",new A(o.Gx,o.Gy,t.ONE)),E(A,"ZERO",new A(t.ZERO,t.ONE,t.ZERO)),E(A,"Fp",t),E(A,"Fn",n);let L=A;const G=n.BITS,O=new Fr(L,e.endo?Math.ceil(G/2):G);return L.BASE.precompute(8),L}function Ts(r){return Uint8Array.of(r?2:3)}function Rs(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yr(r,e={}){const{Fn:s}=r,t=e.randomBytes||as,n=Object.assign(Rs(r.Fp,s),{seed:bs(s.ORDER)});function o(f){try{const w=s.fromBytes(f);return s.isValidNot0(w)}catch{return!1}}function i(f,w){const{publicKey:b,publicKeyUncompressed:y}=n;try{const k=f.length;return w===!0&&k!==b||w===!1&&k!==y?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=t(n.seed)){return Hr(V(f,n.seed,"seed"),s.ORDER)}function c(f,w=!0){return r.BASE.multiply(s.fromBytes(f)).toBytes(w)}function l(f){const{secretKey:w,publicKey:b,publicKeyUncompressed:y}=n;if(!pt(f)||"_lengths"in s&&s._lengths||w===b)return;const k=V(f,void 0,"key").length;return k===b||k===y}function u(f,w,b=!0){if(l(f)===!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(f);return r.fromBytes(w).multiply(y).toBytes(b)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},x=qr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:x,Point:r,utils:h,lengths:n})}function Jr(r,e,s={}){rs(e),gt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||as,n=s.hmac||((_,g)=>Is(e,_,g)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:x,lengths:f}=Yr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*As<o.ORDER;function y(_){const g=a>>Re;return _>g}function k(_,g){if(!i.isValidNot0(g))throw new Error(`invalid signature ${_}: out of range 1..Point.Fn.ORDER`);return g}function N(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function W(_,g){lt(g);const v=f.signature,R=g==="compact"?v:g==="recovered"?v+1:void 0;return V(_,R)}class B{constructor(g,v,R){E(this,"r");E(this,"s");E(this,"recovery");if(this.r=k("r",g),this.s=k("s",v),R!=null){if(N(),![0,1,2,3].includes(R))throw new Error("invalid recovery id");this.recovery=R}Object.freeze(this)}static fromBytes(g,v=w.format){W(g,v);let R;if(v==="der"){const{r:T,s:$}=ye.toSig(V(g));return new B(T,$)}v==="recovered"&&(R=g[0],v="compact",g=g.subarray(1));const D=f.signature/2,C=g.subarray(0,D),M=g.subarray(D,D*2);return new B(i.fromBytes(C),i.fromBytes(M),R)}static fromHex(g,v){return this.fromBytes(qe(g),v)}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:v,s:R}=this,D=this.assertRecovery(),C=D===2||D===3?v+a:v;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(C),T=r.fromBytes(be(Ts((D&1)===0),M)),$=i.inv(C),F=q(V(g,void 0,"msgHash")),J=i.create(-F*$),K=i.create(R*$),H=r.BASE.multiplyUnsafe(J).add(T.multiplyUnsafe(K));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(g=w.format){if(lt(g),g==="der")return qe(ye.hexFromSig(this));const{r:v,s:R}=this,D=i.toBytes(v),C=i.toBytes(R);return g==="recovered"?(N(),be(Uint8Array.of(this.assertRecovery()),D,C)):be(D,C)}toHex(g){return Me(this.toBytes(g))}}const j=s.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const v=je(g),R=g.length*8-c;return R>0?v>>BigInt(R):v},q=s.bits2int_modN||function(g){return i.create(j(g))},P=xt(c);function S(_){return Tr("num < 2^"+c,_,_e,P),i.toBytes(_)}function L(_,g){return V(_,void 0,"message"),g?V(e(_),void 0,"prehashed message"):_}function G(_,g,v){const{lowS:R,prehash:D,extraEntropy:C}=nt(v,w);_=L(_,D);const M=q(_),T=i.fromBytes(g);if(!i.isValidNot0(T))throw new Error("invalid private key");const $=[S(T),S(M)];if(C!=null&&C!==!1){const H=C===!0?t(f.secretKey):C;$.push(V(H,void 0,"extraEntropy"))}const F=be(...$),J=M;function K(H){const X=j(H);if(!i.isValidNot0(X))return;const Z=i.inv(X),oe=r.BASE.multiply(X).toAffine(),z=i.create(oe.x);if(z===_e)return;const Q=i.create(Z*i.create(J+z*T));if(Q===_e)return;let vt=(oe.x===z?0:2)|Number(oe.y&Re),St=Q;return R&&y(Q)&&(St=i.neg(Q),vt^=1),new B(z,St,b?void 0:vt)}return{seed:F,k2sig:K}}function O(_,g,v={}){const{seed:R,k2sig:D}=G(_,g,v);return kr(e.outputLen,i.BYTES,n)(R,D).toBytes(v.format)}function A(_,g,v,R={}){const{lowS:D,prehash:C,format:M}=nt(R,w);if(v=V(v,void 0,"publicKey"),g=L(g,C),!pt(_)){const T=_ instanceof B?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}W(_,M);try{const T=B.fromBytes(_,M),$=r.fromBytes(v);if(D&&T.hasHighS())return!1;const{r:F,s:J}=T,K=q(g),H=i.inv(J),X=i.create(K*H),Z=i.create(F*H),oe=r.BASE.multiplyUnsafe(X).add($.multiplyUnsafe(Z));return oe.is0()?!1:i.create(oe.x)===F}catch{return!1}}function I(_,g,v={}){const{prehash:R}=nt(v,w);return g=L(g,R),B.fromBytes(_,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:x,lengths:f,Point:r,sign:O,verify:A,recoverPublicKey:I,Signature:B,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Xr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Vt=BigInt(2);function Zr(r){const e=wt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,u=l*l*r%e,h=ae(u,s,e)*u%e,x=ae(h,s,e)*u%e,f=ae(x,Vt,e)*l%e,w=ae(f,n,e)*f%e,b=ae(w,o,e)*w%e,y=ae(b,a,e)*b%e,k=ae(y,c,e)*y%e,N=ae(k,a,e)*b%e,W=ae(N,s,e)*u%e,B=ae(W,i,e)*w%e,j=ae(B,t,e)*l%e,q=ae(j,Vt,e);if(!dt.eql(dt.sqr(q),r))throw new Error("Cannot find square root");return q}const dt=Ye(wt.p,{sqrt:Zr}),Qr=jr(wt,{Fp:dt,endo:Xr}),en=Jr(Qr,Er),tn=BigInt(0),Ce=BigInt(1),sn=BigInt(2),rn=BigInt(7),nn=BigInt(256),on=BigInt(113),ks=[],Ps=[],Os=[];for(let r=0,e=Ce,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],ks.push(2*(5*t+s)),Ps.push((r+1)*(r+2)/2%64);let n=tn;for(let o=0;o<7;o++)e=(e<<Ce^(e>>rn)*on)%nn,e&sn&&(n^=Ce<<(Ce<<BigInt(o))-Ce);Os.push(n)}const Cs=xr(Os,!0),an=Cs[0],cn=Cs[1],zt=(r,e,s)=>s>32?wr(r,e,s):gr(r,e,s),jt=(r,e,s)=>s>32?yr(r,e,s):mr(r,e,s);function ln(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],u=s[c+1],h=zt(l,u,1)^s[a],x=jt(l,u,1)^s[a+1];for(let f=0;f<50;f+=10)r[i+f]^=h,r[i+f+1]^=x}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=Ps[i],c=zt(n,o,a),l=jt(n,o,a),u=ks[i];n=r[u],o=r[u+1],r[u]=c,r[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=an[t],r[1]^=cn[t]}Pe(s)}class yt{constructor(e,s,t,n=!1,o=24){E(this,"state");E(this,"pos",0);E(this,"posOut",0);E(this,"finished",!1);E(this,"state32");E(this,"destroyed",!1);E(this,"blockLen");E(this,"suffix");E(this,"outputLen");E(this,"enableXOF",!1);E(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=n,this.rounds=o,ge(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ir(this.state)}clone(){return this._cloneInto()}keccak(){Dt(this.state32),ln(this.state32,this.rounds),Dt(this.state32),this.posOut=0,this.pos=0}update(e){ke(this),V(e);const{blockLen:s,state:t}=this,n=e.length;for(let o=0;o<n;){const i=Math.min(s-this.pos,n-o);for(let a=0;a<i;a++)t[this.pos++]^=e[o++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:n}=this;e[t]^=s,s&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){ke(this,!1),V(e),this.finish();const s=this.state,{blockLen:t}=this;for(let n=0,o=e.length;n<o;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,o-n);e.set(s.subarray(this.posOut,this.posOut+i),n),this.posOut+=i,n+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ge(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ns(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 yt(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 dn=(r,e,s,t={})=>is(()=>new yt(e,r,s),t),Yt=dn(1,136,32),un=60;class hn{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Xe.createRemoteJWKSet(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(s){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",s)}}async verifyJWT(e,s){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+un<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:o}=await Xe.jwtVerify(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:o,valid:!0,signatureVerified:!0}}catch(o){if(o instanceof Error&&(o.name==="JWSSignatureVerificationFailed"||o.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",o),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Xe.decodeJwt(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=Yt(o),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=pn(a),l=c.slice(0,32),u=c.slice(32,64),h=c[64],x=h>=27?h-27:h,b=new en.Signature(Jt(l),Jt(u)).addRecoveryBit(x).recoverPublicKey(i).toBytes(!1).slice(1),y=Yt(b);return"0x"+Me(y.slice(12))}}function pn(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 Jt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const fn=3e4,_n=1e3;class xn{async request(e){const s=e.retries??0;for(let t=0;t<=s;t++){try{const n=await this._doRequest(e);if(n.status<500||t===s)return n}catch(n){if(t===s)throw n}await new Promise(n=>setTimeout(n,_n*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??fn);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:s.signal,credentials:e.credentials});let o;const i=await n.text();try{o=i?JSON.parse(i):null}catch{o={_raw:i}}return{status:n.status,data:o,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const gn=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Ee{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const s=e.split(".");if(s.length<2)throw new Error("Invalid JWT format");const t=(s[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const s=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",s);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,s){const t=Ee.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:o,keys:Object.keys(t)});return}if(o.includes("appleid.apple.com")){const i=await Ee.sha256Hex(s);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=Ee.generateRandom16Hex(),l=Ee.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const x=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!x){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const f=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),B(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,b=30;let y=0,k=null;const N=()=>{clearInterval(W),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+b+"초간 대기합니다"),k=setTimeout(()=>{B(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},b*1e3)},W=setInterval(()=>{y++;try{x.closed&&(y<=w?N():(B(),t(new Error("로그인이 취소되었습니다"))))}catch{N()}},1e3),B=()=>{clearTimeout(f),clearInterval(W),k&&clearTimeout(k),window.removeEventListener("message",j)},j=q=>{if(q.origin!==e.expectedOrigin)return;if(!gn.has(q.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",q.origin),B(),t(new Error("Unauthorized OAuth origin"));return}B();const P=typeof q.data.status=="string",S=P?q.data.data??{}:q.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:P?"wrapped":"flat",status:P?q.data.status:"(flat)"});const L=(S==null?void 0:S.state)??q.data.state;if(!L||L!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(P&&q.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",S==null?void 0:S.error),t(new Error((S==null?void 0:S.error)||"Authentication failed"));return}if(!P&&(S!=null&&S.error)){d.error("[CROSSx] OAuth 실패:",S.error),t(new Error(S.error||"Authentication failed"));return}const G=S==null?void 0:S.idToken,O=S==null?void 0:S.accessToken,A=O??G;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!O,hasIdToken:!!G}),!A){d.error("[CROSSx] 토큰을 찾을 수 없음:",q.data),t(new Error("Token not found in response"));return}const I=_=>{Ee.verifyIdTokenNonce(_,l).then(()=>s(A)).catch(g=>{d.error("[CROSSx] nonce 검증 실패:",g),t(g instanceof Error?g:new Error("nonce verification failed"))})};O?O.split(".").length===3?I(O):G?I(G):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),s(A)):G?I(G):t(new Error("Token not found in response"))};window.addEventListener("message",j)})}}const Ne="crossx_wallet_data",Te="crossx_mock_pin_hash";class mn{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Ne)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Ne);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(Ne,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Te,o),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new m(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Ne);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return d.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return d.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){d.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return d.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Te);return s&&s!==e?!1:(s||await this.storage.set(Te,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new m(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Te);if(n&&t&&n!==t)throw new m(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Te,s),d.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(d.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new m(p.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new m(p.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:s,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Ne,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Te,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class Le{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 m(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 u=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(u&&typeof u.code=="number"){if(u.code<0||u.code>=400){const h=u.message||u.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:u.code,message:h,url:o,method:e});const x=Le.mapGatewayError(u.code,u.data),f=Le.getGatewayErrorMessage(u.code,h),w=u.data,b=x===p.PIN_LOCKED?Le.extractLockDetails(w):w??void 0,y=new m(x,f,b);throw x===p.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(d.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:u.code,url:o,method:e}),u.data??u}return u}catch(l){if(l instanceof m)throw l;if((a=l.response)!=null&&a.data){const u=l.response.data,h=u.message||u.data||"API 요청에 실패했습니다",x=u.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:x,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new m(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${x}): ${h}`)}throw l}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new m(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new m(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new m(p.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new m(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async migrateWallet(e,s){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e};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 m(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:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10007:return p.BROADCAST_FAILED;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10004:return p.WALLET_ALREADY_EXISTS;case-10005:return p.WALLET_NOT_FOUND;case-10011:return p.WALLET_NOT_FOUND;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10013:return p.WITHDRAW_FAILED;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10025:return p.INVALID_APP_TYPE;case-10028:return p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10032:return p.PIN_REPEATED_PATTERN;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;case-10020:return p.CHAIN_NOT_SUPPORTED;case-10021:return p.INVALID_CHAIN;case-10040:return p.HMAC_REQUIRED;case-10041:return p.HMAC_VERIFICATION_FAILED;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${s}`}}}class De{constructor(e,s){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=s}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const s=e.data.chains;return this.populateCache(s,!1),s}catch{const e=De.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(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?sr:tr;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new m(De.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=De.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new m(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(ze).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 Xt="__crossx-confirm-style",te="__crossx-confirm-overlay",wn={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 Zt(r,e){const s=wn[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 yn=`
|
|
3
3
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
4
4
|
|
|
5
5
|
#${te} {
|
|
@@ -1724,7 +1724,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1724
1724
|
opacity: 0.5;
|
|
1725
1725
|
cursor: default;
|
|
1726
1726
|
}
|
|
1727
|
-
`;function he(){let r=document.getElementById(Xt);r||(r=document.createElement("style"),r.id=Xt,document.head.appendChild(r)),r.textContent=yn}function pe(r){const e=s=>s.stopPropagation();for(const s of["pointerdown","pointerup","mousedown","mouseup","click","touchstart","touchend"])r.addEventListener(s,e);document.body.appendChild(r)}function se(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function bn(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=ut(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Qt={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
|
|
1727
|
+
`;function he(){let r=document.getElementById(Xt);r||(r=document.createElement("style"),r.id=Xt,document.head.appendChild(r)),r.textContent=yn}function pe(r){const e=s=>s.stopPropagation();for(const s of["pointerdown","pointerup","mousedown","mouseup","click","touchstart","touchend"])r.addEventListener(s,e);document.body.appendChild(r)}function se(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function bn(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const n=ut(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Qt={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Ns(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Qt[e]?Qt[e]:r}function ut(r,e){if(r===0n)return"0";const s=10n**BigInt(e),t=r/s,i=(r%s).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return i?`${t}.${i}`:`${t}`}function ot(r){try{const e=BigInt(r),s=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${s}.${n}`:`${s}`}catch{return r}}function vn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function Sn(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:o="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=vn(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${ut(l,i)} ${o}`,maxFeeGwei:ot(t),maxPriorityFeeGwei:n?ot(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${ut(l,i)} ${o}`,gasPriceGwei:ot(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ls(r){const e=Sn(r);if(!e)return Y("Estimated fee","<span>—</span>");let s=Y("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=Y("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=Y("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=Y("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=Y("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const xe=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1728
1728
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1729
1729
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1730
1730
|
</svg>`,ie=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
@@ -1748,7 +1748,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1748
1748
|
<span class="__crossx-row-label">${r}</span>
|
|
1749
1749
|
<div class="__crossx-row-value">${e}</div>
|
|
1750
1750
|
</div>`}function Tn(r,e){const s=e,t=Je(r.dappName),n=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
|
|
1751
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1751
|
+
<button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${xe}</button>`:"<span>—</span>",o=Ls(r),i=r.data??"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
|
|
1752
1752
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1753
1753
|
<div class="__crossx-header">
|
|
1754
1754
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1759,7 +1759,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1759
1759
|
<div class="__crossx-body-cols">
|
|
1760
1760
|
<div class="__crossx-col-left">
|
|
1761
1761
|
<p class="__crossx-sig-subtitle">
|
|
1762
|
-
<span class="__crossx-sig-origin">${
|
|
1762
|
+
<span class="__crossx-sig-origin">${U(t)} </span>is requesting a Signature
|
|
1763
1763
|
</p>
|
|
1764
1764
|
<div class="__crossx-addr-pill">
|
|
1765
1765
|
${bt}
|
|
@@ -1771,10 +1771,10 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1771
1771
|
<div class="__crossx-col-right-sign">
|
|
1772
1772
|
<div class="__crossx-rows">
|
|
1773
1773
|
${Y("To",n)}
|
|
1774
|
-
${Y("Network",`<span>${
|
|
1774
|
+
${Y("Network",`<span>${Ns(r.chainId)}</span>`)}
|
|
1775
1775
|
${o}
|
|
1776
1776
|
</div>
|
|
1777
|
-
<pre class="__crossx-raw-tx">${
|
|
1777
|
+
<pre class="__crossx-raw-tx">${U(i)}</pre>
|
|
1778
1778
|
</div>
|
|
1779
1779
|
</div>
|
|
1780
1780
|
<div class="__crossx-btn-row">
|
|
@@ -1784,7 +1784,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1784
1784
|
</div>
|
|
1785
1785
|
</div>
|
|
1786
1786
|
`,a}function Rn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=Je(r.dappName),i=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
|
|
1787
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1787
|
+
<button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${xe}</button>`:"<span>—</span>",a=Ls(r),l=bn(r.value,t,n)??"—",u=document.createElement("div");return u.id=te,u.innerHTML=`
|
|
1788
1788
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1789
1789
|
<div class="__crossx-header">
|
|
1790
1790
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -1793,12 +1793,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1793
1793
|
<hr class="__crossx-divider">
|
|
1794
1794
|
<div class="__crossx-body">
|
|
1795
1795
|
<p class="__crossx-tx-subtitle">
|
|
1796
|
-
<span class="__crossx-sig-origin">${
|
|
1796
|
+
<span class="__crossx-sig-origin">${U(o)}</span> wants your permission to approve the following transaction.
|
|
1797
1797
|
</p>
|
|
1798
1798
|
<div class="__crossx-body-cols">
|
|
1799
1799
|
<div class="__crossx-rows">
|
|
1800
1800
|
${Y("To",i)}
|
|
1801
|
-
${Y("Network",`<span>${
|
|
1801
|
+
${Y("Network",`<span>${Ns(r.chainId)}</span>`)}
|
|
1802
1802
|
${a}
|
|
1803
1803
|
</div>
|
|
1804
1804
|
<div class="__crossx-pill">
|
|
@@ -1809,12 +1809,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1809
1809
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
1810
1810
|
</div>
|
|
1811
1811
|
</div>
|
|
1812
|
-
`,u}function Je(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function
|
|
1813
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1814
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1815
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1812
|
+
`,u}function Je(r){var e;if(r)return r;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function U(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function kn(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function Pn(r){if(typeof r=="string")return U(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return U(JSON.stringify(r))}catch{return String(r)}}function On(r,e){const s=Y("From",`<span class="__crossx-addr-text">${se(r.from)}</span>
|
|
1813
|
+
<button class="__crossx-copy-btn" data-copy="${U(r.from)}" title="Copy address">${xe}</button>`),t=r.to?Y("To",`<span class="__crossx-addr-text">${se(r.to)}</span>
|
|
1814
|
+
<button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${xe}</button>`):"",n=r.amount?Y("Transfer",`<span>${U(r.amount)}</span>`):"",o=r.fees?Y("Tx Fee",`<span>${U(r.fees)}</span>`):"",i=r.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${se(r.txHash)}</span>
|
|
1815
|
+
<button class="__crossx-copy-btn" data-copy="${U(r.txHash)}" title="Copy hash">${xe}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
1816
1816
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1817
|
-
<span class="__crossx-total-amount">${
|
|
1817
|
+
<span class="__crossx-total-amount">${U(r.total)}</span>
|
|
1818
1818
|
</div>`:"",c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
1819
1819
|
<div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1820
1820
|
<div class="__crossx-header">
|
|
@@ -1834,7 +1834,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1834
1834
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
1835
1835
|
</div>
|
|
1836
1836
|
</div>
|
|
1837
|
-
`,c}function
|
|
1837
|
+
`,c}function Cn(r,e){const s=document.createElement("div");return s.id=te,s.innerHTML=`
|
|
1838
1838
|
<div class="__crossx-card __crossx-card--migration" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1839
1839
|
<div class="__crossx-header">
|
|
1840
1840
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -1847,23 +1847,23 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1847
1847
|
</div>
|
|
1848
1848
|
</div>
|
|
1849
1849
|
</div>
|
|
1850
|
-
`,s}function
|
|
1851
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1852
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1853
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1850
|
+
`,s}function Nn(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",o=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(o){const w=n?An:t?"":In,b=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";w?(o.style.display="flex",o.style.alignItems="center",o.style.gap="8px",o.innerHTML=`${w}<span>${b}</span>`):o.textContent=b}if(i&&!r.querySelector("#__crossx-close-btn")){const w=document.createElement("button");w.className="__crossx-close",w.id="__crossx-close-btn",w.setAttribute("aria-label","Close"),w.innerHTML=ie,i.appendChild(w)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?Y("From",`<span class="__crossx-addr-text">${se(e.from)}</span>
|
|
1851
|
+
<button class="__crossx-copy-btn" data-copy="${U(e.from)}" title="Copy address">${xe}</button>`):"",l=e.to?Y("To",`<span class="__crossx-addr-text">${se(e.to)}</span>
|
|
1852
|
+
<button class="__crossx-copy-btn" data-copy="${U(e.to)}" title="Copy address">${xe}</button>`):"",u=e.amount?Y("Transfer",`<span>${U(e.amount)}</span>`):"",h=e.fees?Y("Tx Fee",`<span>${U(e.fees)}</span>`):"",x=e.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${se(e.txHash)}</span>
|
|
1853
|
+
<button class="__crossx-copy-btn" data-copy="${U(e.txHash)}" title="Copy hash">${xe}</button>`):"",f=e.total?`<div class="__crossx-total-pill">
|
|
1854
1854
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1855
|
-
<span class="__crossx-total-amount">${
|
|
1855
|
+
<span class="__crossx-total-amount">${U(e.total)}</span>
|
|
1856
1856
|
</div>`:"";a.innerHTML=`
|
|
1857
1857
|
<div class="__crossx-rows">
|
|
1858
1858
|
${c}
|
|
1859
1859
|
${l}
|
|
1860
1860
|
${u}
|
|
1861
1861
|
${h}
|
|
1862
|
-
${
|
|
1862
|
+
${x}
|
|
1863
1863
|
</div>
|
|
1864
1864
|
${f}
|
|
1865
1865
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1866
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",
|
|
1866
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",b=>{var k;b.stopPropagation();const y=w.dataset.copy;y&&((k=navigator.clipboard)==null||k.writeText(y).catch(()=>{}))})})}function Ln(r,e){const s=e,t=Je(r.dappName),n=U(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
|
|
1867
1867
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1868
1868
|
<div class="__crossx-header">
|
|
1869
1869
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1874,7 +1874,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1874
1874
|
<div class="__crossx-body-cols">
|
|
1875
1875
|
<div class="__crossx-col-left">
|
|
1876
1876
|
<p class="__crossx-sig-subtitle">
|
|
1877
|
-
<span class="__crossx-sig-origin">${
|
|
1877
|
+
<span class="__crossx-sig-origin">${U(t)} </span>is requesting a Signature
|
|
1878
1878
|
</p>
|
|
1879
1879
|
<div class="__crossx-addr-pill">
|
|
1880
1880
|
${bt}
|
|
@@ -1894,11 +1894,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1894
1894
|
`,o}function Dn(r,e){const s=e,t=Je(r.dappName);let n={};if(typeof r.typedData=="string")try{n=JSON.parse(r.typedData)}catch{}else r.typedData&&typeof r.typedData=="object"&&(n=r.typedData);const o=n.primaryType??"—",i=n.message??{};let a=`
|
|
1895
1895
|
<div class="__crossx-td-row">
|
|
1896
1896
|
<span class="__crossx-td-label">Primary Type</span>
|
|
1897
|
-
<span class="__crossx-td-value">${
|
|
1897
|
+
<span class="__crossx-td-value">${U(o)}</span>
|
|
1898
1898
|
</div>`;for(const[l,u]of Object.entries(i)){const h=Pn(u),f=kn(u)?`<span class="__crossx-addr-text">${se(u)}</span>
|
|
1899
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1899
|
+
<button class="__crossx-copy-btn" data-copy="${U(String(u))}" title="Copy">${xe}</button>`:`<span>${h}</span>`;a+=`
|
|
1900
1900
|
<div class="__crossx-td-row">
|
|
1901
|
-
<span class="__crossx-td-label">${
|
|
1901
|
+
<span class="__crossx-td-label">${U(l)}</span>
|
|
1902
1902
|
<div class="__crossx-td-value">${f}</div>
|
|
1903
1903
|
</div>`}const c=document.createElement("div");return c.id=te,c.innerHTML=`
|
|
1904
1904
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
@@ -1911,7 +1911,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1911
1911
|
<div class="__crossx-body-cols">
|
|
1912
1912
|
<div class="__crossx-col-left">
|
|
1913
1913
|
<p class="__crossx-sig-subtitle">
|
|
1914
|
-
<span class="__crossx-sig-origin">${
|
|
1914
|
+
<span class="__crossx-sig-origin">${U(t)} </span>is requesting a Signature
|
|
1915
1915
|
</p>
|
|
1916
1916
|
<div class="__crossx-addr-pill">
|
|
1917
1917
|
${bt}
|
|
@@ -1931,7 +1931,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
1931
1931
|
`,c}const Mn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
1932
1932
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
1933
1933
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
1934
|
-
</svg>`;function $n(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${
|
|
1934
|
+
</svg>`;function $n(r,e,s){const t=s==null?void 0:s.toLowerCase(),n=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${U(i.address)}">
|
|
1935
1935
|
<span class="__crossx-wallet-addr">${se(i.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
1936
1936
|
</button>`}).join(""),o=document.createElement("div");return o.id=te,o.innerHTML=`
|
|
1937
1937
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${ce(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
@@ -2070,12 +2070,12 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2070
2070
|
`,{overlay:a,startCountdown:l=>{if(n||!o)return()=>{};const h=setInterval(()=>{Date.now()>=o&&(clearInterval(h),l())},1e3);return()=>clearInterval(h)}}}function Kn(r){const s=[r.check1,r.check2].map((t,n)=>`
|
|
2071
2071
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2072
2072
|
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${jn}</div>
|
|
2073
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
2073
|
+
<span class="__crossx-pw-notice-item-text">${U(t)}</span>
|
|
2074
2074
|
</div>
|
|
2075
2075
|
`).join("");return`
|
|
2076
2076
|
<div class="__crossx-header">
|
|
2077
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2078
|
-
<p class="__crossx-pw-subtitle">${
|
|
2077
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${U(r.title)}</p>
|
|
2078
|
+
<p class="__crossx-pw-subtitle">${U(r.headerSubtitle)}</p>
|
|
2079
2079
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
|
|
2080
2080
|
</div>
|
|
2081
2081
|
<hr class="__crossx-divider">
|
|
@@ -2084,27 +2084,27 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2084
2084
|
<div class="__crossx-pw-notice-header">
|
|
2085
2085
|
<div class="__crossx-pw-notice-title-row">
|
|
2086
2086
|
<span class="__crossx-pw-notice-icon">${Yn}</span>
|
|
2087
|
-
<p class="__crossx-pw-notice-title">${
|
|
2087
|
+
<p class="__crossx-pw-notice-title">${U(r.noticeTitle)}</p>
|
|
2088
2088
|
</div>
|
|
2089
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2089
|
+
<p class="__crossx-pw-notice-desc">${U(r.noticeDesc)}</p>
|
|
2090
2090
|
</div>
|
|
2091
2091
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2092
2092
|
${s}
|
|
2093
2093
|
</div>
|
|
2094
2094
|
</div>
|
|
2095
2095
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2096
|
-
data-next-label="${
|
|
2097
|
-
data-submit-label="${
|
|
2098
|
-
${
|
|
2096
|
+
data-next-label="${U(r.nextButton)}"
|
|
2097
|
+
data-submit-label="${U(r.submitButton)}">
|
|
2098
|
+
${U(r.nextButton)}
|
|
2099
2099
|
</button>
|
|
2100
2100
|
</div>
|
|
2101
2101
|
<div class="__crossx-home-indicator"></div>
|
|
2102
|
-
`}function it(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${
|
|
2102
|
+
`}function it(r){const e=!!r.lockExpiresAt&&r.lockExpiresAt>Date.now(),s=r.lockExpiresAt?` data-lock-expires="${r.lockExpiresAt}"`:"",t=r.headerSubtitle?`<p class="__crossx-pin6-header-sub">${U(r.headerSubtitle)}</p>`:"",n=r.subtitle?`<p class="__crossx-pin6-subtitle">${U(r.subtitle)}</p>`:"",o=r.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${U(r.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',i=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2103
2103
|
${Ds}
|
|
2104
2104
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2105
2105
|
</p>`:"",a=e?" --locked":"",c=Array.from({length:6},(l,u)=>`<input class="__crossx-pin6-box${a}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${u+1}"${e?" disabled":""}>`).join("");return`
|
|
2106
2106
|
<div class="__crossx-header">
|
|
2107
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2107
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${U(r.title)}</p>
|
|
2108
2108
|
${t}
|
|
2109
2109
|
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
|
|
2110
2110
|
</div>
|
|
@@ -2122,10 +2122,10 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
|
|
|
2122
2122
|
<div class="__crossx-card __crossx-card--pin6" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2123
2123
|
${e}
|
|
2124
2124
|
</div>
|
|
2125
|
-
`,s}function Vn(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((o,i)=>i===0||o===(s[i-1]+1)%10),n=s.every((o,i)=>i===0||o===(s[i-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function zn(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function at(r,e,s,t,n,o){var
|
|
2125
|
+
`,s}function Vn(r,e){if(r.length!==6)return e.tooShort;if(!/^\d+$/.test(r))return e.numbersOnly;if(/(.)\1{2}/.test(r))return e.repeatingDigit;const s=r.split("").map(Number),t=s.every((o,i)=>i===0||o===(s[i-1]+1)%10),n=s.every((o,i)=>i===0||o===(s[i-1]+9)%10);return t||n?e.sequential:r[0]!==r[1]&&r===r.slice(0,2).repeat(3)?e.alternatingPattern:null}function zn(r){const e=Math.max(0,Math.ceil(r/1e3)),s=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return s>0?`${s}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function at(r,e,s,t,n,o){var j,q;let i=!!(o&&o>Date.now()),a=!1;const c=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),l=()=>r.querySelector("#__crossx-pin6-boxes"),u=()=>r.querySelector("#__crossx-pin6-error"),h=()=>r.querySelector("#__crossx-pin6-lock-msg"),x=()=>r.querySelector("#__crossx-pin6-lock-countdown"),f=()=>r.querySelector(".__crossx-pin6-body"),w=()=>c().map(P=>P.value).join(""),b=P=>{i=P,c().forEach(S=>{S.disabled=P,S.classList.toggle("--locked",P)})},y=()=>{const P=u();P&&(P.textContent="")},k=P=>{const S=u();S&&(S.textContent=P);const L=l();L==null||L.classList.add("--shake"),setTimeout(()=>L==null?void 0:L.classList.remove("--shake"),500),c().forEach(G=>{G.value=""}),setTimeout(()=>{var G;return(G=c()[0])==null?void 0:G.focus()},50)},N=P=>{var A;b(!0),c().forEach(I=>{I.value=""});const S=u();if(S&&(S.textContent="Too many failed attempts. Please wait."),!h()){const I=document.createElement("p");I.className="__crossx-pin6-lock-msg",I.id="__crossx-pin6-lock-msg",I.innerHTML=`${Ds}<span id="__crossx-pin6-lock-countdown"></span>`;const _=u();_?_.insertAdjacentElement("afterend",I):(A=f())==null||A.appendChild(I)}const L=()=>{var g;const I=P-Date.now(),_=x();I<=0?(clearInterval(G),b(!1),(g=h())==null||g.remove(),S&&(S.textContent=""),setTimeout(()=>{var v;return(v=c()[0])==null?void 0:v.focus()},50)):_&&(_.textContent=` ${zn(I)}`)},G=setInterval(L,1e3);L();const O=new MutationObserver(()=>{document.contains(r)||(clearInterval(G),O.disconnect())});O.observe(document.body,{childList:!0,subtree:!1})},W=async()=>{if(i||a)return;const P=w();if(P.length===6){a=!0,c().forEach(S=>{S.disabled=!0});try{if(n){const S=await n(P);S.ok?e(P):S.lockExpiresAt?N(S.lockExpiresAt):k(S.error??"Incorrect PIN. Please try again.")}else e(P)}catch(S){t&&t(S)}finally{a=!1,i||c().forEach(S=>{S.disabled=!1})}}};o&&o>Date.now()?N(o):setTimeout(()=>{var P;return(P=c()[0])==null?void 0:P.focus()},100);const B=()=>{if(i||a)return;const P=c(),S=P.find(L=>!L.value)??P[P.length-1];S==null||S.focus()};(j=l())==null||j.addEventListener("click",P=>{P.target.classList.contains("__crossx-pin6-box")||B()}),(q=f())==null||q.addEventListener("click",P=>{const S=P.target;S.classList.contains("__crossx-pin6-box")||S.closest("button")||B()}),c().forEach((P,S)=>{P.addEventListener("input",()=>{var G;const L=P.value.replace(/\D/g,"").slice(-1);P.value=L,y(),L&&S<5&&((G=c()[S+1])==null||G.focus()),w().length===6&&setTimeout(W,80)}),P.addEventListener("keydown",L=>{var G,O;if(L.key==="Backspace"){if(L.preventDefault(),P.value)P.value="";else if(S>0){const A=c()[S-1];A.value="",A.focus()}}else L.key==="ArrowLeft"&&S>0?(L.preventDefault(),(G=c()[S-1])==null||G.focus()):L.key==="ArrowRight"&&S<5?(L.preventDefault(),(O=c()[S+1])==null||O.focus()):L.key==="Escape"&&s()}),P.addEventListener("paste",L=>{var A,I;L.preventDefault();const G=(((A=L.clipboardData)==null?void 0:A.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!G)return;const O=c();G.split("").forEach((_,g)=>{O[g]&&(O[g].value=_)}),(I=O[Math.min(G.length-1,5)])==null||I.focus(),y(),w().length===6&&setTimeout(W,80)}),P.addEventListener("focus",()=>P.select())})}const Ds=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2126
2126
|
<path d="M14.5 8.5H14V6.5C14 4.015 11.985 2 9.5 2C7.015 2 5 4.015 5 6.5V8.5H4.5C3.672 8.5 3 9.172 3 10V16.5C3 17.328 3.672 18 4.5 18H14.5C15.328 18 16 17.328 16 16.5V10C16 9.172 15.328 8.5 14.5 8.5ZM10.5 13.415V15C10.5 15.276 10.276 15.5 10 15.5H9C8.724 15.5 8.5 15.276 8.5 15V13.415C8.187 13.196 8 12.847 8 12.5C8 11.672 8.672 11 9.5 11C10.328 11 11 11.672 11 12.5C11 12.847 10.813 13.196 10.5 13.415ZM12.5 8.5H6.5V6.5C6.5 4.843 7.843 3.5 9.5 3.5C11.157 3.5 12.5 4.843 12.5 6.5V8.5Z" fill="currentColor"/>
|
|
2127
2127
|
</svg>`,jn=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2128
2128
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2129
2129
|
</svg>`,Yn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2130
2130
|
<path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="currentColor"/>
|
|
2131
|
-
</svg>`;function Jn(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var h;c.preventDefault();const l=(((h=c.clipboardData)==null?void 0:h.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,f)=>{t[f]&&(t[f].value=g)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class Xn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Zt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Zt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var v;he();const o=[...e],i=$n(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",pe(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},u=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const S=y.dataset.walletAddress??"",C=parseInt(y.dataset.walletIndex??"0",10);u({address:S,index:C})})})})();const f=i.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.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">${se(y.address)}</span>`,C.addEventListener("click",()=>u(y)),S.appendChild(C),C.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(v=i.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(e){return new Promise(s=>{var c,l,u,h;he();const t=Hn(this.tokens,e==null?void 0:e.showConnectOtherWallets);pe(t);const n=()=>t.remove(),o=g=>{n(),s(g)},i=()=>{n(),s(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>o("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>o("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>o("external")),(h=t.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",i),t.addEventListener("click",g=>{g.target===t&&i()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(g=>{g.addEventListener("click",f=>f.stopPropagation())});const a=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;he();const n=Fn(this.tokens,s);pe(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),s){const u=()=>{o(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",g=>{g.target===n&&u()});const h=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)}})}showPinSetupPrompt(e){return new Promise(s=>{he();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=es(this.tokens,Kn(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",pe(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=C=>{u(),s(C)},g=()=>{u(),s(null)},f=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."},v=C=>{var U;f.innerHTML=it({title:i.title,headerSubtitle:i.headerSubtitle}),(U=f.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",g),at(f,O=>{O===C?h(C):y(o.mismatchError)},g)},y=C=>{var U;f.innerHTML=it({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:C}),(U=f.querySelector("#__crossx-close-btn"))==null||U.addEventListener("click",g),at(f,O=>{const V=Vn(O,w);V?y(V):v(O)},g)};(()=>{var q;const C=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),U=f.querySelector("#__crossx-pin-notice-next"),O=new Set;U.removeAttribute("disabled");const V=U.dataset.nextLabel??"Next",W=U.dataset.submitLabel??"I Understand",P=()=>{const L=O.size===C.length;U.classList.toggle("--disabled",!L),U.textContent=L?W:V},k=(L,R)=>{if(O.has(R))return;const A=L.querySelector(`#__crossx-notice-check-${R}`);O.add(R),A.classList.add("--checked"),L.setAttribute("aria-checked","true"),P()},D=(L,R)=>{if(!O.has(R))return;const A=L.querySelector(`#__crossx-notice-check-${R}`);O.delete(R),A.classList.remove("--checked"),L.setAttribute("aria-checked","false"),P()};C.forEach(L=>{const R=parseInt(L.dataset.checkIndex??"0",10);L.addEventListener("click",()=>{O.has(R)?D(L,R):k(L,R)}),L.addEventListener("keydown",A=>{(A.key===" "||A.key==="Enter")&&(A.preventDefault(),O.has(R)?D(L,R):k(L,R))})}),U.addEventListener("click",()=>{if(O.size===C.length){y(e==null?void 0:e.errorMessage);return}const L=C.find(A=>{const _=parseInt(A.dataset.checkIndex??"0",10);return!O.has(_)});if(!L)return;const R=parseInt(L.dataset.checkIndex??"0",10);L.scrollIntoView({behavior:"smooth",block:"nearest"}),L.classList.add("--highlight"),setTimeout(()=>{L.classList.remove("--highlight"),k(L,R)},400)}),(q=f.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",g)})(),a.addEventListener("click",C=>{C.target===a&&g()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;he();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=es(this.tokens,it({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",pe(c);let u=!1;const h=()=>{u||(u=!0,c.remove(),document.body.style.overflow=l)},g=S=>{h(),s(S)},f=()=>{h(),s(null)},w=S=>{h(),t(S)},v=c.querySelector(".__crossx-card");(y=v.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",f),at(v,g,f,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",S=>{S.target===c&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;he();const t=Gn(this.tokens,e);pe(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};Jn(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;he();const{overlay:n,startCountdown:o}=qn(this.tokens,e,s);pe(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;he();const t=On(e,this.tokens);pe(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var g;u.stopPropagation();const h=l.dataset.copy;h&&((g=navigator.clipboard)==null||g.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=>{he();const n=Nn(e,this.tokens);pe(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,h;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Cn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,u;he();let t;e.type==="sign-message"?t=Ln(e,this.tokens):e.type==="sign-typed-data"?t=Dn(e,this.tokens):e.type==="sign"?t=Tn(e,this.tokens):t=Rn(e,this.tokens),pe(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),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",g=>{var w;g.stopPropagation();const f=h.dataset.copy;f&&((w=navigator.clipboard)==null||w.writeText(f).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 Ms{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}}function Zn(r,e){r.debug;const s=Ge.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},o=t.authMode!=="cookie"&&Lt.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new Lt(r.projectId):new rr,a=new hn,c=new xn,l=new be,u=new Ms,h=new ht;let g;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),g=new mn(i,h)):(d.log("[CROSSx] Remote Wallet Provider 사용"),g=new Le(n,i,c,u,h));const f=new De(n,c),w=new Xn(r.theme??"light",r.themeTokens),v=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w;return new We(t,n,i,a,c,l,g,u,v,f,h)}exports.CROSSxError=m;exports.CROSSxEthereumProvider=ts;exports.CROSSxSDK=We;exports.ChainId=Us;exports.ErrorCode=p;exports.PinMemoryStore=ht;exports.TokenMemoryStore=Ms;exports.createCROSSxSDK=Zn;
|
|
2131
|
+
</svg>`;function Jn(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((i,a)=>{i.addEventListener("input",()=>{const c=i.value.replace(/\D/g,"");i.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),i.addEventListener("keydown",c=>{c.key==="Backspace"&&!i.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&s()}),i.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),i.addEventListener("paste",c=>{var h;c.preventDefault();const l=(((h=c.clipboardData)==null?void 0:h.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((x,f)=>{t[f]&&(t[f].value=x)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=r.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",i=>{if(!i.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(o=t[0])==null||o.focus()}class Xn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Zt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Zt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var b;he();const o=[...e],i=$n(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",pe(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},u=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const k=y.dataset.walletAddress??"",N=parseInt(y.dataset.walletIndex??"0",10);u({address:k,index:N})})})})();const f=i.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.disabled=!0;try{const y=await s();o.push(y);const k=i.querySelector("#__crossx-wallet-list");if(k){const N=document.createElement("button");N.className="__crossx-wallet-item",N.dataset.walletIndex=String(y.index),N.dataset.walletAddress=y.address,N.innerHTML=`<span class="__crossx-wallet-addr">${se(y.address)}</span>`,N.addEventListener("click",()=>u(y)),k.appendChild(N),N.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(b=i.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(e){return new Promise(s=>{var c,l,u,h;he();const t=Hn(this.tokens,e==null?void 0:e.showConnectOtherWallets);pe(t);const n=()=>t.remove(),o=x=>{n(),s(x)},i=()=>{n(),s(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>o("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>o("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>o("external")),(h=t.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",i),t.addEventListener("click",x=>{x.target===t&&i()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(x=>{x.addEventListener("click",f=>f.stopPropagation())});const a=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}showMigrationFoundPrompt(e){const s=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;he();const n=Fn(this.tokens,s);pe(n);const o=()=>n.remove(),i=()=>{o(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",i),s){const u=()=>{o(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",x=>{x.target===n&&u()});const h=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",h),u())};document.addEventListener("keydown",h)}})}showPinSetupPrompt(e){return new Promise(s=>{he();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=es(this.tokens,Kn(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",pe(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=N=>{u(),s(N)},x=()=>{u(),s(null)},f=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},b=N=>{var W;f.innerHTML=it({title:i.title,headerSubtitle:i.headerSubtitle}),(W=f.querySelector("#__crossx-close-btn"))==null||W.addEventListener("click",x),at(f,B=>{B===N?h(N):y(o.mismatchError)},x)},y=N=>{var W;f.innerHTML=it({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:N}),(W=f.querySelector("#__crossx-close-btn"))==null||W.addEventListener("click",x),at(f,B=>{const j=Vn(B,w);j?y(j):b(B)},x)};(()=>{var G;const N=Array.from(f.querySelectorAll(".__crossx-pw-notice-item")),W=f.querySelector("#__crossx-pin-notice-next"),B=new Set;W.removeAttribute("disabled");const j=W.dataset.nextLabel??"Next",q=W.dataset.submitLabel??"I Understand",P=()=>{const O=B.size===N.length;W.classList.toggle("--disabled",!O),W.textContent=O?q:j},S=(O,A)=>{if(B.has(A))return;const I=O.querySelector(`#__crossx-notice-check-${A}`);B.add(A),I.classList.add("--checked"),O.setAttribute("aria-checked","true"),P()},L=(O,A)=>{if(!B.has(A))return;const I=O.querySelector(`#__crossx-notice-check-${A}`);B.delete(A),I.classList.remove("--checked"),O.setAttribute("aria-checked","false"),P()};N.forEach(O=>{const A=parseInt(O.dataset.checkIndex??"0",10);O.addEventListener("click",()=>{B.has(A)?L(O,A):S(O,A)}),O.addEventListener("keydown",I=>{(I.key===" "||I.key==="Enter")&&(I.preventDefault(),B.has(A)?L(O,A):S(O,A))})}),W.addEventListener("click",()=>{if(B.size===N.length){y(e==null?void 0:e.errorMessage);return}const O=N.find(I=>{const _=parseInt(I.dataset.checkIndex??"0",10);return!B.has(_)});if(!O)return;const A=parseInt(O.dataset.checkIndex??"0",10);O.scrollIntoView({behavior:"smooth",block:"nearest"}),O.classList.add("--highlight"),setTimeout(()=>{O.classList.remove("--highlight"),S(O,A)},400)}),(G=f.querySelector("#__crossx-close-btn"))==null||G.addEventListener("click",x)})(),a.addEventListener("click",N=>{N.target===a&&x()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;he();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=es(this.tokens,it({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",pe(c);let u=!1;const h=()=>{u||(u=!0,c.remove(),document.body.style.overflow=l)},x=k=>{h(),s(k)},f=()=>{h(),s(null)},w=k=>{h(),t(k)},b=c.querySelector(".__crossx-card");(y=b.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",f),at(b,x,f,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",k=>{k.target===c&&f()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;he();const t=Gn(this.tokens,e);pe(t);const n=()=>t.remove(),o=c=>{n(),s(c)},i=()=>{n(),s(null)};Jn(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;he();const{overlay:n,startCountdown:o}=qn(this.tokens,e,s);pe(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;he();const t=On(e,this.tokens);pe(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var x;u.stopPropagation();const h=l.dataset.copy;h&&((x=navigator.clipboard)==null||x.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=>{he();const n=Cn(e,this.tokens);pe(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var u,h;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",x=>{x.target===n&&a()});const l=x=>{x.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Nn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,u;he();let t;e.type==="sign-message"?t=Ln(e,this.tokens):e.type==="sign-typed-data"?t=Dn(e,this.tokens):e.type==="sign"?t=Tn(e,this.tokens):t=Rn(e,this.tokens),pe(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),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",x=>{var w;x.stopPropagation();const f=h.dataset.copy;f&&((w=navigator.clipboard)==null||w.writeText(f).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 Ms{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const s=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof s.exp=="number"?s.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}}function Zn(r,e){r.debug;const s=Ge.production,t={...r,oauthServiceUrl:s.oauthServiceUrl,authApiUrl:s.authApiUrl,walletGatewayUrl:s.walletGatewayUrl},n={gatewayUrl:s.walletGatewayUrl,projectId:r.projectId},o=t.authMode!=="cookie"&&Lt.isAvailable();!o&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=o;const i=o?new Lt(r.projectId):new rr,a=new hn,c=new xn,l=new Ee,u=new Ms,h=new ht;let x;r.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),x=new mn(i,h)):(d.log("[CROSSx] Remote Wallet Provider 사용"),x=new Le(n,i,c,u,h));const f=new De(n,c),w=new Xn(r.theme??"light",r.themeTokens),b=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w,y=new We(t,n,i,a,c,l,x,u,b,f,h);return typeof window<"u"&&(window.__crossxSDK=y),y}function Qn(r){const e=eo(r),s=to(e),t=JSON.parse(s);ro(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function eo(r){if(r.includes("://")&&r.includes("?")){const e=new URL(r),s=e.searchParams.get("crossx_oauth_result");if(s)return s;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return r}function to(r){if(r.startsWith("{"))return r;if(r.startsWith("%7B")||r.startsWith("%7b"))return decodeURIComponent(r);const e=so(r);return decodeURIComponent(e)}function so(r){if(typeof atob=="function")return atob(r);if(typeof Buffer<"u")return Buffer.from(r,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function ro(r){if(typeof r!="object"||r===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=r;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const s=e.data;if(typeof s.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof s.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}exports.CROSSxError=m;exports.CROSSxEthereumProvider=ts;exports.CROSSxSDK=We;exports.ChainId=Us;exports.ErrorCode=p;exports.PinMemoryStore=ht;exports.TokenMemoryStore=Ms;exports.createCROSSxSDK=Zn;exports.parseOAuthDeeplink=Qn;
|