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

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/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var Os=Object.defineProperty;var Ls=(r,e,s)=>e in r?Os(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var I=(r,e,s)=>Ls(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ds=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.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_CANCELLED="PIN_CANCELLED",r.PIN_LOCKED="PIN_LOCKED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class _ extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,_.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Ms=Object.fromEntries(Object.entries(je).map(([r,e])=>[r,e.caipId])),$s=new Map(Object.values(je).map(r=>[r.caipId,r]));new Map(Object.values(je).map(r=>[r.chainId,r]));const Bs={symbol:"",decimals:18};function Xe(r){var e;return((e=$s.get(r))==null?void 0:e.nativeCurrency)??Bs}class Zt{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 _(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new _(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 be=null;function vt(r){be=r}const u={log(...r){if(be){be.log(...r);return}},warn(...r){if(be){be.warn(...r);return}},error(...r){if(be){be.error(...r);return}}},Us={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",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:"이용 가능 시간"},Xt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from"},Hs={ko:Us,en:Xt};function St(r="en",e){return Hs[r]??Xt}const $e="crossx_access_token",Re="crossx_refresh_token",Ce="crossx_user_info";class Fs{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new _(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 _(p.AUTH_FAILED,`${s} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:h}=this.config,m=`${d}${l}`;u.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const g=await this.oauth.openAuth({authUrl:m,expectedOrigin:new URL(d).origin});u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",g.length,")");const{accessToken:w,refreshToken:E}=await this.exchangeFirebaseToken(g,h);let y,S;try{const B=this.crypto.decodeJWT(g);S=(n=B.firebase)==null?void 0:n.sign_in_provider;const v=((o=B.firebase)==null?void 0:o.identities)??{};S==="google.com"?y=(i=v["google.com"])==null?void 0:i[0]:S==="apple.com"&&(y=(a=v["apple.com"])==null?void 0:a[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",S,"hasProviderSub:",!!y)}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const B=this.crypto.decodeJWT(w);u.log("[CROSSx] access_token 디코딩 — sub:",B.sub,"exp:",B.exp);const v=await this.crypto.verifyJWT(w);if(t=v.signatureVerified??!1,!v.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const P=v.payload;s={id:P.sub,email:P.email,signInProvider:S,providerSub:y},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set($e,w),E&&await this.storage.set(Re,E))}else{const B=this.crypto.decodeJWT(g);s={id:B.sub,email:B.email,signInProvider:S,providerSub:y},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}u.log("[CROSSx] 사용자 정보 — id:",s.id);const O=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Ce,O),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return u.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Ce);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get($e),n=await this.storage.get(Re);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Ce);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return u.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Re),await this.storage.remove(Ce),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new _(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set($e,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Re,l)}return u.log("[CROSSx] silentRefresh 성공"),c}async executeWithJWT(e,s){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!s)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;u.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set($e,e),s&&await this.storage.set(Re,s)),await this.storage.set(Ce,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return u.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",o),o==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof _&&o.code===p.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof _&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Gs="crossx_access_token",Ws="crossx_refresh_token",qs="crossx_user_info";class Vs{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(Gs),await this.storage.remove(Ws)),await this.storage.remove(qs)}}class zs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new _(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Qt{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 Ks{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new _(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class js{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const We={production:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function Ys(r){const e=r.environment;return e&&e in We?We[e]:null}function 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 We.production}const Zs=2e3,It=6e4,Xs=1e3,Qs=1e4,er="0x77359400",Et="0x3B9ACA00",Tt=130,At=6,kt=18,tr=0,sr=30*1e3,re=class re extends js{constructor(e,s,t,n,o,i,a,c,l,d,h){var m;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&vt(e.logger),this.confirmation=l,this.pinStore=h??new Qt,this.chainRegistry=d,this.jsonRpc=new Ks(d,o),this.signInUseCase=new Fs(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Vs(this.internalConfig,t,c),this.migrateWalletUseCase=new zs(t,a),(m=a.setOnUnauthorized)==null||m.call(a,()=>this.forceLogout())}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){console.log("[CROSSx SDK] v1.2.0 초기화 중..."),this.confirmation.setMessages(St(this._config.locale));try{const s=Js();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl;const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){this.applyAuthResult(t);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(n){if(!(n instanceof _&&n.code===p.PIN_CANCELLED))throw n;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(t!=null&&t.success)}),t??null}catch(s){throw new _(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new _(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new _(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 _&&t.code===p.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new _(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new _(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new _(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof _&&s.code===p.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof _?s:new _(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(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 _(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 _?e:new _(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof _?s:new _(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(St(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new _(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof _&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new _(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof _&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new _(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePinForSigning();const n=await this.resolveAddress(t==null?void 0:t.index);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const a=await this.withPinRetry(()=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,o,n.address));return this.verifySignatureSigner(s,a.signature,n.address),{chainId:e,signature:a.signature,message:s,address:n.address}}catch(a){throw a instanceof _?a:new _(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,a)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(p.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");await this.ensurePinForSigning(),re.validateTypedDataChainId(e,s);const n=await this.resolveAddress(t==null?void 0:t.index);let o;if(this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const a=await this.withPinRetry(()=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,o,n.address));return re.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:n.address}}catch(a){throw a instanceof _?a:new _(p.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,a)}}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 _(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePinForSigning();const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("sign",{tx:n})).uuid);const i=Xe(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const c=await this.withPinRetry(()=>this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o));return re.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof _)throw c;const l=c instanceof Error?c.message:String(c);throw new _(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new _(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePinForSigning();const n=await this.withResolvedGasAndFee(s,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);let o;this.walletProvider.prepare&&(o=(await this.walletProvider.prepare("send",{tx:n})).uuid);const i=Xe(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new _(p.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const c=await this.withPinRetry(async()=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,o)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,o);return l.txHash??l.signature});return{chainId:e,txHash:c,status:"pending"}}catch(c){if(c instanceof _)throw c;const l=c instanceof Error?c.message:String(c);throw new _(p.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${l}`,c)}}async getTransactionReceipt(e,s){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],s)??null}catch{return null}}async waitForTxAndGetReceipt(e,s,t={}){const n=t.intervalMs??Xs,o=Qs,i=t.timeoutMs??It,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new _(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var E,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??Zs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??It,d=Xe(e),h=s.from??"";let m,g;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{m=S;const O=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),B=s.value?BigInt(s.value):0n,v=re.formatTxAmount(s.value,d.symbol,d.decimals),P=re.formatTxAmount("0x"+O.toString(16),d.symbol,d.decimals),C=re.formatTxAmount("0x"+(B+O).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:S.from,to:S.to??s.to,amount:v,fees:P,total:C,nativeSymbol:d.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(g=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:h,to:s.to,amount:re.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:s.to},w),g)throw g;return{chainId:e,txHash:a,receipt:m}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new _(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof _?n:new _(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 _(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 _(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 _(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 _(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 _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(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 _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(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(kt),n=s/t,i=(s%t).toString().padStart(kt,"0").replace(/0+$/,"").slice(0,At);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Zt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof _)throw n;const o=n instanceof Error?n.message:String(n);throw new _(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,At).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0,o=5,i=null;for(;;){n++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:t,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(l===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${l.length}자리) — verify-recovery-pin API 호출`),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyRecoveryPin)==null?void 0:c.call(a,l,e));if(!d){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const h=d.pinStatus;if(o=h.maxAttempts,n=o-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const m=h.lockExpiresAt*1e3,g=Math.max(1,Math.round((m-Date.now())/1e3)),w=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${g}초, 메시지: ${w}`),await this.confirmation.showRecoveryPinLockedPrompt(g,w),n=0,t="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),t="Incorrect PIN."}catch(d){if(!(d instanceof _))throw d;if(d.code===p.MIGRATION_PIN_LOCKED){const h=d.details;if(o=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const m=((h==null?void 0:h.lockExpiresAt)??0)*1e3,g=Math.max(1,Math.round((m-Date.now())/1e3)),w=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${g}초`),await this.confirmation.showRecoveryPinLockedPrompt(g,w),n=0,t="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",d),d}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const l=await this.migrateWalletUseCase.execute(i,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof _&&l.code===p.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=Et;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=er,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Et,u.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 _(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 _(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new _(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 _(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Tt)throw new _(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Tt} 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 _(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new _(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var s,t,n,o;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=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&&(u.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new _(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new _(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s});if(!i)throw new _(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}if(!await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof _){if(c.code===p.PIN_WRONG)return{ok:!1,error:"Incorrect PIN. Please try again."};if(c.code===p.PIN_LOCKED)return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:(a=c.details)==null?void 0:a.lockExpiresAt}}throw c}}}))throw new _(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");t()}catch(o){throw n(o),o}finally{this._verifyPinMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let s,t;try{return await e()}catch(n){if(n instanceof _)if(n.code===p.PIN_WRONG)s="Incorrect PIN. Please enter your current PIN.";else if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked."}else throw n;else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",s),this.pinStore.clear(),await this.ensureVerifiedPin(s,t),t=void 0;try{return await e()}catch(n){if(n instanceof _){if(n.code===p.PIN_WRONG){s="Incorrect PIN. Please try again.";continue}if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked.";continue}}throw n}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new _(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 _(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new _(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),vt(null)}};re.OFFCHAIN_CHAIN_ID="0";let qe=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 u.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const nr="crossx-sdk",or=1,Ie="data",Be="keys",Pt="aes-primary",ir=12;class Rt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(nr,or);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Ie)||n.createObjectStore(Ie),n.objectStoreNames.contains(Be)||n.createObjectStore(Be)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Be,Pt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Be,Pt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(ir);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(Ie,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Ie,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Ie,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Ie)}catch(e){throw u.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 ut(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function xe(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=ut(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 es(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");xe(r.outputLen),xe(r.blockLen)}function Ae(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 ts(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 ar(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function ke(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Qe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function de(r,e){return r<<32-e|r>>>e}const cr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function dr(r){for(let e=0;e<r.length;e++)r[e]=lr(r[e]);return r}const Ct=cr?r=>r:dr,ss=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ur=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Me(r){if(z(r),ss)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=ur[r[s]];return e}const he={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nt(r){if(r>=he._0&&r<=he._9)return r-he._0;if(r>=he.A&&r<=he.F)return r-(he.A-10);if(r>=he.a&&r<=he.f)return r-(he.a-10)}function Ve(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ss)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=Nt(r.charCodeAt(o)),a=Nt(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 ye(...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 rs(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 ns(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 hr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function pr(r,e,s){return r&e^~r&s}function fr(r,e,s){return r&e^r&s^e&s}class xr{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=Qe(this.buffer)}update(e){Ae(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=Qe(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){Ae(this),ts(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,ke(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=Qe(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],o)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const _e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ue=BigInt(2**32-1),Ot=BigInt(32);function _r(r,e=!1){return e?{h:Number(r&Ue),l:Number(r>>Ot&Ue)}:{h:Number(r>>Ot&Ue)|0,l:Number(r&Ue)|0}}function gr(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 mr=(r,e,s)=>r<<s|e>>>32-s,wr=(r,e,s)=>e<<s|r>>>32-s,yr=(r,e,s)=>e<<s-32|r>>>64-s,br=(r,e,s)=>r<<s-32|e>>>64-s,vr=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]),ge=new Uint32Array(64);class Sr extends xr{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)ge[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const m=ge[h-15],g=ge[h-2],w=de(m,7)^de(m,18)^m>>>3,E=de(g,17)^de(g,19)^g>>>10;ge[h]=E+ge[h-7]+w+ge[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){const m=de(a,6)^de(a,11)^de(a,25),g=d+m+pr(a,c,l)+vr[h]+ge[h]|0,E=(de(t,2)^de(t,13)^de(t,22))+fr(t,n,o)|0;d=l,l=c,c=a,a=i+g|0,i=o,o=n,n=t,t=g+E|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){ke(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),ke(this.buffer)}}class Ir extends Sr{constructor(){super(32);I(this,"A",_e[0]|0);I(this,"B",_e[1]|0);I(this,"C",_e[2]|0);I(this,"D",_e[3]|0);I(this,"E",_e[4]|0);I(this,"F",_e[5]|0);I(this,"G",_e[6]|0);I(this,"H",_e[7]|0)}}const Er=rs(()=>new Ir,hr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ht=BigInt(0),at=BigInt(1);function ze(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function os(r){if(typeof r=="bigint"){if(!Ge(r))throw new Error("positive bigint expected, got "+r)}else xe(r);return r}function He(r){const e=os(r).toString(16);return e.length&1?"0"+e:e}function is(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ht:BigInt("0x"+r)}function Ye(r){return is(Me(r))}function as(r){return is(Me(Tr(z(r)).reverse()))}function pt(r,e){xe(e),r=os(r);const s=Ve(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function cs(r,e){return pt(r,e).reverse()}function Tr(r){return Uint8Array.from(r)}const Ge=r=>typeof r=="bigint"&&ht<=r;function Ar(r,e,s){return Ge(r)&&Ge(e)&&Ge(s)&&e<=r&&r<s}function kr(r,e,s,t){if(!Ar(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Pr(r){let e;for(e=0;r>ht;r>>=at,e+=1);return e}const ft=r=>(at<<BigInt(r))-at;function Rr(r,e,s){if(xe(r,"hashLen"),xe(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const h=()=>{c.fill(1),l.fill(0),d=0},m=(...y)=>s(l,ye(c,...y)),g=(y=n)=>{l=m(o,y),c=m(),y.length!==0&&(l=m(i,y),c=m())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const S=[];for(;y<e;){c=m();const O=c.slice();S.push(O),y+=c.length}return ye(...S)};return(y,S)=>{h(),g(y);let O;for(;!(O=S(w()));)g();return h(),O}}function xt(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 Lt(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),ve=BigInt(2),ls=BigInt(3),ds=BigInt(4),us=BigInt(5),Cr=BigInt(7),hs=BigInt(8),Nr=BigInt(9),ps=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 Dt(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 _t(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function fs(r,e){const s=(r.ORDER+ee)/ds,t=r.pow(e,s);return _t(r,t,e),t}function Or(r,e){const s=(r.ORDER-us)/hs,t=r.mul(e,ve),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,ve),n),a=r.mul(o,r.sub(i,r.ONE));return _t(r,a,e),a}function Lr(r){const e=Je(r),s=xs(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Cr)/ps;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const h=a.mul(l,n),m=a.mul(l,o),g=a.eql(a.sqr(d),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,d,g),d=a.cmov(m,h,w);const E=a.eql(a.sqr(d),c),y=a.cmov(l,d,E);return _t(a,y,c),y}}function xs(r){if(r<ls)throw new Error("sqrt is not defined for small field");let e=r-ee,s=0;for(;e%ve===ne;)e/=ve,s++;let t=ve;const n=Je(r);for(;Mt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return fs;let o=n.pow(t,e);const i=(e+ee)/ve;return function(c,l){if(c.is0(l))return l;if(Mt(c,l)!==1)throw new Error("Cannot find square root");let d=s,h=c.mul(c.ONE,o),m=c.pow(l,e),g=c.pow(l,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let w=1,E=c.sqr(m);for(;!c.eql(E,c.ONE);)if(w++,E=c.sqr(E),w===d)throw new Error("Cannot find square root");const y=ee<<BigInt(d-w-1),S=c.pow(h,y);d=w,h=c.sqr(S),m=c.mul(m,h),g=c.mul(g,S)}return g}}function Dr(r){return r%ds===ls?fs:r%hs===us?Or:r%ps===Nr?Lr(r):xs(r)}const Mr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $r(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Mr.reduce((t,n)=>(t[n]="function",t),e);return xt(r,s),r}function Br(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 _s(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 Mt(r,e){const s=(r.ORDER-ee)/ve,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 Ur(r,e){e!==void 0&&xe(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Hr{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}=Ur(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 Br(this,e,s)}div(e,s){return le(e*Dt(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 Dt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Dr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?cs(e,this.BYTES):pt(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?as(e):Ye(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 _s(this,e)}cmov(e,s,t){return t?s:e}}function Je(r,e={}){return new Hr(r,e)}function gs(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 ms(r){const e=gs(r);return e+Math.ceil(e/2)}function Fr(r,e,s=!1){z(r);const t=r.length,n=gs(e),o=ms(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?as(r):Ye(r),a=le(i,e-ee)+ee;return s?cs(a,n):pt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pe=BigInt(0),Se=BigInt(1);function Ke(r,e){const s=e.negate();return r?s:e}function $t(r,e){const s=_s(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function ws(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function et(r,e){ws(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=ft(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Bt(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+=Se);const l=e*t,d=l+Math.abs(a)-1,h=a===0,m=a<0,g=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:m,isNegF:g,offsetF:l}}const tt=new WeakMap,ys=new WeakMap;function st(r){return ys.get(r)||1}function Ut(r){if(r!==Pe)throw new Error("invalid wNAF")}class Gr{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>Pe;)s&Se&&(t=t.add(n)),n=n.double(),s>>=Se;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=et(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=et(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:m,offsetF:g}=Bt(t,a,i);t=c,d?o=o.add(Ke(m,s[g])):n=n.add(Ke(h,s[l]))}return Ut(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=et(e,this.bits);for(let i=0;i<o.windows&&t!==Pe;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Bt(t,i,o);if(t=a,!l){const h=s[c];n=n.add(d?h.negate():h)}}return Ut(t),n}getPrecomputes(e,s,t){let n=tt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),tt.set(s,n))),n}cached(e,s,t){const n=st(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=st(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){ws(s,this.bits),ys.set(e,s),tt.delete(e)}hasCache(e){return st(e)!==1}}function Wr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Pe||t>Pe;)s&Se&&(o=o.add(n)),t&Se&&(i=i.add(n)),n=n.double(),s>>=Se,t>>=Se;return{p1:o,p2:i}}function Ht(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $r(e),e}else return Je(r,{isLE:s})}function qr(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>Pe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Ht(e.p,s.Fp,t),o=Ht(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 Vr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class bs{constructor(e,s){I(this,"oHash");I(this,"iHash");I(this,"blockLen");I(this,"outputLen");I(this,"finished",!1);I(this,"destroyed",!1);if(es(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),ke(n)}update(e){return Ae(this),this.iHash.update(e),this}digestInto(e){Ae(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 vs=(r,e,s)=>new bs(r,e).update(s).digest();vs.create=(r,e)=>new bs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ft=(r,e)=>(r+(r>=0?e:-e)/Ss)/e;function zr(r,e,s){const[[t,n],[o,i]]=e,a=Ft(i*r,s),c=Ft(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const h=l<pe,m=d<pe;h&&(l=-l),m&&(d=-d);const g=ft(Math.ceil(Pr(s)/2))+Te;if(l<pe||l>=g||d<pe||d>=g)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:m,k2:d}}function ct(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function rt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ze(s.lowS,"lowS"),ze(s.prehash,"prehash"),s.format!==void 0&&ct(s.format),s}class Kr extends Error{constructor(e=""){super(e)}}const me={Err:Kr,_tlv:{encode:(r,e)=>{const{Err:s}=me;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=He(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?He(n.length/2|128):"";return He(r)+o+n+e},decode(r,e){const{Err:s}=me;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=me;if(r<pe)throw new e("integer: negative integers are not allowed");let s=He(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}=me;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 Ye(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=me,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:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=me,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},pe=BigInt(0),Te=BigInt(1),Ss=BigInt(2),Fe=BigInt(3),jr=BigInt(4);function Yr(r,e={}){const s=qr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;xt(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=Es(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(R,f,x){const{x:b,y:A}=f.toAffine(),L=t.toBytes(b);if(ze(x,"isCompressed"),x){d();const N=!t.isOdd(A);return ye(Is(N),L)}else return ye(Uint8Array.of(4),L,t.toBytes(A))}function m(R){z(R,void 0,"Point");const{publicKey:f,publicKeyUncompressed:x}=l,b=R.length,A=R[0],L=R.subarray(1);if(b===f&&(A===2||A===3)){const N=t.fromBytes(L);if(!t.isValid(N))throw new Error("bad point: is not on curve, wrong x");const M=E(N);let T;try{T=t.sqrt(M)}catch(J){const V=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const $=t.isOdd(T);return(A&1)===1!==$&&(T=t.neg(T)),{x:N,y:T}}else if(b===x&&A===4){const N=t.BYTES,M=t.fromBytes(L.subarray(0,N)),T=t.fromBytes(L.subarray(N,N*2));if(!y(M,T))throw new Error("bad point: is not on curve");return{x:M,y:T}}else throw new Error(`bad point: got length ${b}, expected compressed=${f} or uncompressed=${x}`)}const g=e.toBytes||h,w=e.fromBytes||m;function E(R){const f=t.sqr(R),x=t.mul(f,R);return t.add(t.add(x,t.mul(R,o.a)),o.b)}function y(R,f){const x=t.sqr(f),b=E(R);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,Fe),jr),O=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(S,O)))throw new Error("bad curve params: a or b");function B(R,f,x=!1){if(!t.isValid(f)||x&&t.is0(f))throw new Error(`bad point coordinate ${R}`);return f}function v(R){if(!(R instanceof W))throw new Error("Weierstrass Point expected")}function P(R){if(!c||!c.basises)throw new Error("no endo");return zr(R,c.basises,n.ORDER)}const C=Lt((R,f)=>{const{X:x,Y:b,Z:A}=R;if(t.eql(A,t.ONE))return{x,y:b};const L=R.is0();f==null&&(f=L?t.ONE:t.inv(A));const N=t.mul(x,f),M=t.mul(b,f),T=t.mul(A,f);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:N,y:M}}),G=Lt(R=>{if(R.is0()){if(e.allowInfinityPoint&&!t.is0(R.Y))return;throw new Error("bad point: ZERO")}const{x:f,y:x}=R.toAffine();if(!t.isValid(f)||!t.isValid(x))throw new Error("bad point: x or y not field elements");if(!y(f,x))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function K(R,f,x,b,A){return x=new W(t.mul(x.X,R),x.Y,x.Z),f=Ke(b,f),x=Ke(A,x),f.add(x)}const k=class k{constructor(f,x,b){I(this,"X");I(this,"Y");I(this,"Z");this.X=B("x",f),this.Y=B("y",x,!0),this.Z=B("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(f){const{x,y:b}=f||{};if(!f||!t.isValid(x)||!t.isValid(b))throw new Error("invalid affine point");if(f instanceof k)throw new Error("projective point not allowed");return t.is0(x)&&t.is0(b)?k.ZERO:new k(x,b,t.ONE)}static fromBytes(f){const x=k.fromAffine(w(z(f,void 0,"point")));return x.assertValidity(),x}static fromHex(f){return k.fromBytes(Ve(f))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,x=!0){return D.createCache(this,f),x||this.multiply(Fe),this}assertValidity(){G(this)}hasEvenY(){const{y:f}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(f)}equals(f){v(f);const{X:x,Y:b,Z:A}=this,{X:L,Y:N,Z:M}=f,T=t.eql(t.mul(x,M),t.mul(L,A)),$=t.eql(t.mul(b,M),t.mul(N,A));return T&&$}negate(){return new k(this.X,t.neg(this.Y),this.Z)}double(){const{a:f,b:x}=o,b=t.mul(x,Fe),{X:A,Y:L,Z:N}=this;let M=t.ZERO,T=t.ZERO,$=t.ZERO,F=t.mul(A,A),J=t.mul(L,L),V=t.mul(N,N),H=t.mul(A,L);return H=t.add(H,H),$=t.mul(A,N),$=t.add($,$),M=t.mul(f,$),T=t.mul(b,V),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(b,$),V=t.mul(f,V),H=t.sub(F,V),H=t.mul(f,H),H=t.add(H,$),$=t.add(F,F),F=t.add($,F),F=t.add(F,V),F=t.mul(F,H),T=t.add(T,F),V=t.mul(L,N),V=t.add(V,V),F=t.mul(V,H),M=t.sub(M,F),$=t.mul(V,J),$=t.add($,$),$=t.add($,$),new k(M,T,$)}add(f){v(f);const{X:x,Y:b,Z:A}=this,{X:L,Y:N,Z:M}=f;let T=t.ZERO,$=t.ZERO,F=t.ZERO;const J=o.a,V=t.mul(o.b,Fe);let H=t.mul(x,L),Z=t.mul(b,N),X=t.mul(A,M),oe=t.add(x,b),j=t.add(L,N);oe=t.mul(oe,j),j=t.add(H,Z),oe=t.sub(oe,j),j=t.add(x,A);let Q=t.add(L,M);return j=t.mul(j,Q),Q=t.add(H,X),j=t.sub(j,Q),Q=t.add(b,A),T=t.add(N,M),Q=t.mul(Q,T),T=t.add(Z,X),Q=t.sub(Q,T),F=t.mul(J,j),T=t.mul(V,X),F=t.add(T,F),T=t.sub(Z,F),F=t.add(Z,F),$=t.mul(T,F),Z=t.add(H,H),Z=t.add(Z,H),X=t.mul(J,X),j=t.mul(V,j),Z=t.add(Z,X),X=t.sub(H,X),X=t.mul(J,X),j=t.add(j,X),H=t.mul(Z,j),$=t.add($,H),H=t.mul(Q,j),T=t.mul(oe,T),T=t.sub(T,H),H=t.mul(oe,Z),F=t.mul(Q,F),F=t.add(F,H),new k(T,$,F)}subtract(f){return this.add(f.negate())}is0(){return this.equals(k.ZERO)}multiply(f){const{endo:x}=e;if(!n.isValidNot0(f))throw new Error("invalid scalar: out of range");let b,A;const L=N=>D.cached(this,N,M=>$t(k,M));if(x){const{k1neg:N,k1:M,k2neg:T,k2:$}=P(f),{p:F,f:J}=L(M),{p:V,f:H}=L($);A=J.add(H),b=K(x.beta,F,V,N,T)}else{const{p:N,f:M}=L(f);b=N,A=M}return $t(k,[b,A])[0]}multiplyUnsafe(f){const{endo:x}=e,b=this;if(!n.isValid(f))throw new Error("invalid scalar: out of range");if(f===pe||b.is0())return k.ZERO;if(f===Te)return b;if(D.hasCache(this))return this.multiply(f);if(x){const{k1neg:A,k1:L,k2neg:N,k2:M}=P(f),{p1:T,p2:$}=Wr(k,b,L,M);return K(x.beta,T,$,A,N)}else return D.unsafe(b,f)}toAffine(f){return C(this,f)}isTorsionFree(){const{isTorsionFree:f}=e;return i===Te?!0:f?f(k,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:f}=e;return i===Te?this:f?f(k,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(f=!0){return ze(f,"isCompressed"),this.assertValidity(),g(k,this,f)}toHex(f=!0){return Me(this.toBytes(f))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};I(k,"BASE",new k(o.Gx,o.Gy,t.ONE)),I(k,"ZERO",new k(t.ZERO,t.ONE,t.ZERO)),I(k,"Fp",t),I(k,"Fn",n);let W=k;const q=n.BITS,D=new Gr(W,e.endo?Math.ceil(q/2):q);return W.BASE.precompute(8),W}function Is(r){return Uint8Array.of(r?2:3)}function Es(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Jr(r,e={}){const{Fn:s}=r,t=e.randomBytes||ns,n=Object.assign(Es(r.Fp,s),{seed:ms(s.ORDER)});function o(g){try{const w=s.fromBytes(g);return s.isValidNot0(w)}catch{return!1}}function i(g,w){const{publicKey:E,publicKeyUncompressed:y}=n;try{const S=g.length;return w===!0&&S!==E||w===!1&&S!==y?!1:!!r.fromBytes(g)}catch{return!1}}function a(g=t(n.seed)){return Fr(z(g,n.seed,"seed"),s.ORDER)}function c(g,w=!0){return r.BASE.multiply(s.fromBytes(g)).toBytes(w)}function l(g){const{secretKey:w,publicKey:E,publicKeyUncompressed:y}=n;if(!ut(g)||"_lengths"in s&&s._lengths||w===E)return;const S=z(g,void 0,"key").length;return S===E||S===y}function d(g,w,E=!0){if(l(g)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(g);return r.fromBytes(w).multiply(y).toBytes(E)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=Vr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:h,lengths:n})}function Zr(r,e,s={}){es(e),xt(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||ns,n=s.hmac||((f,x)=>vs(e,f,x)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:g}=Jr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=a*Ss<o.ORDER;function y(f){const x=a>>Te;return f>x}function S(f,x){if(!i.isValidNot0(x))throw new Error(`invalid signature ${f}: out of range 1..Point.Fn.ORDER`);return x}function O(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(f,x){ct(x);const b=g.signature,A=x==="compact"?b:x==="recovered"?b+1:void 0;return z(f,A)}class v{constructor(x,b,A){I(this,"r");I(this,"s");I(this,"recovery");if(this.r=S("r",x),this.s=S("s",b),A!=null){if(O(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(x,b=w.format){B(x,b);let A;if(b==="der"){const{r:T,s:$}=me.toSig(z(x));return new v(T,$)}b==="recovered"&&(A=x[0],b="compact",x=x.subarray(1));const L=g.signature/2,N=x.subarray(0,L),M=x.subarray(L,L*2);return new v(i.fromBytes(N),i.fromBytes(M),A)}static fromHex(x,b){return this.fromBytes(Ve(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 v(this.r,this.s,x)}recoverPublicKey(x){const{r:b,s:A}=this,L=this.assertRecovery(),N=L===2||L===3?b+a:b;if(!o.isValid(N))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(N),T=r.fromBytes(ye(Is((L&1)===0),M)),$=i.inv(N),F=C(z(x,void 0,"msgHash")),J=i.create(-F*$),V=i.create(A*$),H=r.BASE.multiplyUnsafe(J).add(T.multiplyUnsafe(V));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(x=w.format){if(ct(x),x==="der")return Ve(me.hexFromSig(this));const{r:b,s:A}=this,L=i.toBytes(b),N=i.toBytes(A);return x==="recovered"?(O(),ye(Uint8Array.of(this.assertRecovery()),L,N)):ye(L,N)}toHex(x){return Me(this.toBytes(x))}}const P=s.bits2int||function(x){if(x.length>8192)throw new Error("input is too large");const b=Ye(x),A=x.length*8-c;return A>0?b>>BigInt(A):b},C=s.bits2int_modN||function(x){return i.create(P(x))},G=ft(c);function K(f){return kr("num < 2^"+c,f,pe,G),i.toBytes(f)}function W(f,x){return z(f,void 0,"message"),x?z(e(f),void 0,"prehashed message"):f}function q(f,x,b){const{lowS:A,prehash:L,extraEntropy:N}=rt(b,w);f=W(f,L);const M=C(f),T=i.fromBytes(x);if(!i.isValidNot0(T))throw new Error("invalid private key");const $=[K(T),K(M)];if(N!=null&&N!==!1){const H=N===!0?t(g.secretKey):N;$.push(z(H,void 0,"extraEntropy"))}const F=ye(...$),J=M;function V(H){const Z=P(H);if(!i.isValidNot0(Z))return;const X=i.inv(Z),oe=r.BASE.multiply(Z).toAffine(),j=i.create(oe.x);if(j===pe)return;const Q=i.create(X*i.create(J+j*T));if(Q===pe)return;let yt=(oe.x===j?0:2)|Number(oe.y&Te),bt=Q;return A&&y(Q)&&(bt=i.neg(Q),yt^=1),new v(j,bt,E?void 0:yt)}return{seed:F,k2sig:V}}function D(f,x,b={}){const{seed:A,k2sig:L}=q(f,x,b);return Rr(e.outputLen,i.BYTES,n)(A,L).toBytes(b.format)}function k(f,x,b,A={}){const{lowS:L,prehash:N,format:M}=rt(A,w);if(b=z(b,void 0,"publicKey"),x=W(x,N),!ut(f)){const T=f instanceof v?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}B(f,M);try{const T=v.fromBytes(f,M),$=r.fromBytes(b);if(L&&T.hasHighS())return!1;const{r:F,s:J}=T,V=C(x),H=i.inv(J),Z=i.create(V*H),X=i.create(F*H),oe=r.BASE.multiplyUnsafe(Z).add($.multiplyUnsafe(X));return oe.is0()?!1:i.create(oe.x)===F}catch{return!1}}function R(f,x,b={}){const{prehash:A}=rt(b,w);return x=W(x,A),v.fromBytes(f,"recovered").recoverPublicKey(x).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:g,Point:r,sign:D,verify:k,recoverPublicKey:R,Signature:v,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Xr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Gt=BigInt(2);function Qr(r){const e=gt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,h=ae(d,s,e)*d%e,m=ae(h,s,e)*d%e,g=ae(m,Gt,e)*l%e,w=ae(g,n,e)*g%e,E=ae(w,o,e)*w%e,y=ae(E,a,e)*E%e,S=ae(y,c,e)*y%e,O=ae(S,a,e)*E%e,B=ae(O,s,e)*d%e,v=ae(B,i,e)*w%e,P=ae(v,t,e)*l%e,C=ae(P,Gt,e);if(!lt.eql(lt.sqr(C),r))throw new Error("Cannot find square root");return C}const lt=Je(gt.p,{sqrt:Qr}),en=Yr(gt,{Fp:lt,endo:Xr}),tn=Zr(en,Er),sn=BigInt(0),Ne=BigInt(1),rn=BigInt(2),nn=BigInt(7),on=BigInt(256),an=BigInt(113),Ts=[],As=[],ks=[];for(let r=0,e=Ne,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Ts.push(2*(5*t+s)),As.push((r+1)*(r+2)/2%64);let n=sn;for(let o=0;o<7;o++)e=(e<<Ne^(e>>nn)*an)%on,e&rn&&(n^=Ne<<(Ne<<BigInt(o))-Ne);ks.push(n)}const Ps=gr(ks,!0),cn=Ps[0],ln=Ps[1],Wt=(r,e,s)=>s>32?yr(r,e,s):mr(r,e,s),qt=(r,e,s)=>s>32?br(r,e,s):wr(r,e,s);function dn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],d=s[c+1],h=Wt(l,d,1)^s[a],m=qt(l,d,1)^s[a+1];for(let g=0;g<50;g+=10)r[i+g]^=h,r[i+g+1]^=m}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=As[i],c=Wt(n,o,a),l=qt(n,o,a),d=Ts[i];n=r[d],o=r[d+1],r[d]=c,r[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=cn[t],r[1]^=ln[t]}ke(s)}class mt{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,xe(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ar(this.state)}clone(){return this._cloneInto()}keccak(){Ct(this.state32),dn(this.state32,this.rounds),Ct(this.state32),this.posOut=0,this.pos=0}update(e){Ae(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){Ae(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 xe(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ts(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,ke(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new mt(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 un=(r,e,s,t={})=>rs(()=>new mt(e,r,s),t),Vt=un(1,136,32);class hn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ds.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=Vt(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),d=c.slice(32,64),h=c[64],m=h>=27?h-27:h,E=new tn.Signature(zt(l),zt(d)).addRecoveryBit(m).recoverPublicKey(i).toBytes(!1).slice(1),y=Vt(E);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 zt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const fn=3e4;class xn{async request(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)}}}class we{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=we.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n==="")throw u.error("[CROSSx] nonce claim 누락 — JWT payload 전체 키 목록:",Object.keys(t)),u.error("[CROSSx] 원인 추정: OAuth 서버가 Google/Apple 인증 요청에 nonce 파라미터를 포함하지 않았을 수 있습니다.","서버 로그에서 /auth/google, /auth/apple 요청 URL에 nonce 쿼리가 있는지 확인하세요."),new Error("ID Token에 nonce claim이 없습니다 — OAuth 서버 설정을 확인해 주세요");if(o.includes("appleid.apple.com")){const i=await we.sha256Hex(s);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=we.generateRandom16Hex(),l=we.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const m=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!m){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const g=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),v(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,E=30;let y=0,S=null;const O=()=>{clearInterval(B),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),S=setTimeout(()=>{v(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},B=setInterval(()=>{y++;try{m.closed&&(y<=w?O():(v(),t(new Error("로그인이 취소되었습니다"))))}catch{O()}},1e3),v=()=>{clearTimeout(g),clearInterval(B),S&&clearTimeout(S),window.removeEventListener("message",P)},P=C=>{var K,W,q,D,k;if(C.origin!==e.expectedOrigin)return;v(),u.log("[CROSSx] OAuth postMessage 수신 — status:",C.data.status);const G=C.data.state??((K=C.data.data)==null?void 0:K.state);if(!G||G!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(C.data.status==="success"){const R=(W=C.data.data)==null?void 0:W.idToken,f=(q=C.data.data)==null?void 0:q.accessToken,x=f??R;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!f,hasIdToken:!!R}),!x){u.error("[CROSSx] 토큰을 찾을 수 없음:",C.data),t(new Error("Token not found in response"));return}if(R){try{const b=we.parseJwtPayload(R);u.log("[CROSSx] idToken JWT payload 요약:",{iss:b.iss,sub:typeof b.sub=="string"?`${b.sub.slice(0,6)}...`:"(absent)",hasNonceClaim:"nonce"in b,nonceClaimType:typeof b.nonce,appleNonceSupported:b.nonce_supported??"(field absent)"})}catch{u.warn("[CROSSx] idToken JWT payload 파싱 실패 — 토큰 형식을 확인하세요")}we.verifyIdTokenNonce(R,l).then(()=>s(x)).catch(b=>{u.error("[CROSSx] nonce 검증 실패:",b),t(b instanceof Error?b:new Error("nonce verification failed"))})}else s(x)}else u.error("[CROSSx] OAuth 실패:",(D=C.data.data)==null?void 0:D.error),t(new Error(((k=C.data.data)==null?void 0:k.error)||"Authentication failed"))};window.addEventListener("message",P)})}}const Oe="crossx_wallet_data",Ee="crossx_mock_pin_hash";class _n{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Oe)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Oe);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(Oe,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Ee,o),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new _(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Oe);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return u.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return u.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){u.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return u.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Ee);return s&&s!==e?!1:(s||await this.storage.set(Ee,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new _(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Ee);if(n&&t&&n!==t)throw new _(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ee,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new _(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 _(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(Oe,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Ee,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class 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 _(p.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const h=d.message||d.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:h,url:o,method:e,fullResponse:d});const m=Le.mapGatewayError(d.code,d.data),g=Le.getGatewayErrorMessage(d.code,h),w=d.data,E=m===p.PIN_LOCKED?Le.extractLockDetails(w):w??void 0,y=new _(m,g,E);throw y.gatewayCode=d.code,y.gatewayMessage=h,m===p.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(u.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof _)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,h=d.message||d.data||"API 요청에 실패했습니다",m=d.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:m,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new _(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${m}): ${h}`)}throw l}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new _(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new _(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 _(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async migrateWallet(e,s){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).verified}async changePin(e,s){const t={password:this.requirePin(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new _(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??e,t=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);return t?{lockExpiresAt:t>1e10?t:t*1e3}:{}}static mapGatewayError(e,s){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10028:return p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Invalid PIN format. Please enter a 6-digit numeric PIN.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";default:return`Request failed (${e}): ${s}`}}}class 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 _(De.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=De.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new _(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(je).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 Kt="__crossx-confirm-style",te="__crossx-confirm-overlay",gn={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 jt(r,e){const s=gn[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const mn=`
1
+ "use strict";var Os=Object.defineProperty;var Ls=(r,e,s)=>e in r?Os(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var I=(r,e,s)=>Ls(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ds=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.SIGN_FAILED="SIGN_FAILED",r.SIGN_REJECTED="SIGN_REJECTED",r.TX_FAILED="TX_FAILED",r.TX_REJECTED="TX_REJECTED",r.USER_REJECTED="USER_REJECTED",r.TX_INVALID_PARAMS="TX_INVALID_PARAMS",r.NETWORK_ERROR="NETWORK_ERROR",r.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",r.INVALID_CHAIN="INVALID_CHAIN",r.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",r.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",r.NOT_IMPLEMENTED="NOT_IMPLEMENTED",r.SIGNATURE_FAILED="SIGNATURE_FAILED",r.TRANSACTION_FAILED="TRANSACTION_FAILED",r.PREPARE_FAILED="PREPARE_FAILED",r.PREPARE_EXPIRED="PREPARE_EXPIRED",r.PREPARE_MISMATCH="PREPARE_MISMATCH",r.MIGRATION_FAILED="MIGRATION_FAILED",r.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",r.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",r.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",r.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",r.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",r.PROJECT_ID_MISSING="PROJECT_ID_MISSING",r.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",r.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",r.INVALID_APP_TYPE="INVALID_APP_TYPE",r.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",r.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",r.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",r.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",r.PIN_NOT_SET="PIN_NOT_SET",r.PIN_WRONG="PIN_WRONG",r.PIN_INVALID="PIN_INVALID",r.PIN_CANCELLED="PIN_CANCELLED",r.PIN_LOCKED="PIN_LOCKED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(p||{});class x extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const je={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Ms=Object.fromEntries(Object.entries(je).map(([r,e])=>[r,e.caipId])),$s=new Map(Object.values(je).map(r=>[r.caipId,r]));new Map(Object.values(je).map(r=>[r.chainId,r]));const Bs={symbol:"",decimals:18};function Xe(r){var e;return((e=$s.get(r))==null?void 0:e.nativeCurrency)??Bs}class Zt{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 x(p.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(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 be=null;function vt(r){be=r}const u={log(...r){if(be){be.log(...r);return}},warn(...r){if(be){be.warn(...r);return}},error(...r){if(be){be.error(...r);return}}},Us={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",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:"이용 가능 시간"},Xt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from"},Hs={ko:Us,en:Xt};function St(r="en",e){return Hs[r]??Xt}const $e="crossx_access_token",Re="crossx_refresh_token",Ne="crossx_user_info";class Fs{constructor(e,s,t,n,o,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=n,this.transport=o,this.walletProvider=i,this.tokenStore=a,this._refreshPromise=null}get useCookieAuth(){return this.config.authMode==="cookie"}checkResponseError(e,s){if(e!=null&&e.code&&e.code!==200&&e.code>0)throw new x(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 x(p.AUTH_FAILED,`${s} 실패 (코드 ${n.code}): ${n.message}`)}}async execute(e){var n,o,i,a;let s,t=!1;try{const c=e==null?void 0:e.provider;let l="/login";c==="google"?l="/google":c==="apple"&&(l="/apple");const{oauthServiceUrl:d,authApiUrl:h}=this.config,m=`${d}${l}`;u.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const g=await this.oauth.openAuth({authUrl:m,expectedOrigin:new URL(d).origin});u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",g.length,")");const{accessToken:w,refreshToken:E}=await this.exchangeFirebaseToken(g,h);let y,S;try{const B=this.crypto.decodeJWT(g);S=(n=B.firebase)==null?void 0:n.sign_in_provider;const v=((o=B.firebase)==null?void 0:o.identities)??{};S==="google.com"?y=(i=v["google.com"])==null?void 0:i[0]:S==="apple.com"&&(y=(a=v["apple.com"])==null?void 0:a[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",S,"hasProviderSub:",!!y)}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(w){const B=this.crypto.decodeJWT(w);u.log("[CROSSx] access_token 디코딩 — sub:",B.sub,"exp:",B.exp);const v=await this.crypto.verifyJWT(w);if(t=v.signatureVerified??!1,!v.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const P=v.payload;s={id:P.sub,email:P.email,signInProvider:S,providerSub:y},this.tokenStore.set(w),this.useCookieAuth||(await this.storage.set($e,w),E&&await this.storage.set(Re,E))}else{const B=this.crypto.decodeJWT(g);s={id:B.sub,email:B.email,signInProvider:S,providerSub:y},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}u.log("[CROSSx] 사용자 정보 — id:",s.id);const O=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Ne,O),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return u.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,n=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",o.status);const i=o.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(p.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(i)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const s=(e==null?void 0:e.data)??e;if(this.isJwtString(s))return s;if(typeof s=="object"&&s!==null){const t=s;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.access_token??o.token;if(typeof i=="string")return i}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const s=(e==null?void 0:e.data)??e;if(typeof s!="object"||s===null)return;const t=s;if(typeof t.data=="object"&&t.data!==null){const o=t.data,i=o.refresh_token??o.refresh;if(typeof i=="string")return i}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(Ne);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get($e),n=await this.storage.get(Re);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const o=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",o?"토큰 발급 성공":"토큰 없음"),o&&this.tokenStore.set(o)}const s=await this.storage.get(Ne);if(u.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return u.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Re),await this.storage.remove(Ne),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,n=`${s}/cross-auth/social/refresh/simple`,o={};if(!t){const l=this.tokenStore.get()??"";l&&(o.access_token=l),e&&(o.refresh_token=e)}const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:o,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new x(p.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set($e,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Re,l)}return u.log("[CROSSx] silentRefresh 성공"),c}async executeWithJWT(e,s){let t,n=!1;try{let o=await this.crypto.verifyJWT(e);if(n=o.signatureVerified??!1,!o.valid){if(!s)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(s);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,o=await this.crypto.verifyJWT(e),n=o.signatureVerified??!1,!o.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const i=o.payload;u.log("[CROSSx] signInWithJWT — sub:",i.sub,"signatureVerified:",n),t={id:i.sub,email:i.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set($e,e),s&&await this.storage.set(Re,s)),await this.storage.set(Ne,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(o){return u.error("[CROSSx] signInWithJWT 에러:",o),{success:!1,error:o instanceof Error?o.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async loadWallet(e,s){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const o=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",o),o==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(o==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(o){if(o instanceof x&&o.code===p.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(o instanceof x&&(o.code===p.PROJECT_NOT_REGISTERED||o.code===p.PROJECT_ID_MISSING||o.code===p.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",o.message),o;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",o)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:s}}}const Gs="crossx_access_token",Ws="crossx_refresh_token",qs="crossx_user_info";class Vs{constructor(e,s,t){this.config=e,this.storage=s,this.tokenStore=t}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(Gs),await this.storage.remove(Ws)),await this.storage.remove(qs)}}class zs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new x(p.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class Qt{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 Ks{constructor(e,s){this.chainRegistry=e,this.transport=s}async call(e,s,t){const n=await this.chainRegistry.getChain(t),o={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:o})).data;if(a!=null&&a.error)throw new x(p.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class js{constructor(){this.listeners=new Map}on(e,s){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(s),()=>this.off(e,s)}off(e,s){var t;(t=this.listeners.get(e))==null||t.delete(s)}emit(e,s){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(s))}removeAllListeners(){this.listeners.clear()}}const We={production:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function Ys(r){const e=r.environment;return e&&e in We?We[e]:null}function 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 We.production}const Zs=2e3,It=6e4,Xs=1e3,Qs=1e4,er="0x77359400",Et="0x3B9ACA00",Tt=130,At=6,kt=18,tr=0,sr=30*1e3,re=class re extends js{constructor(e,s,t,n,o,i,a,c,l,d,h){var m;super(),this.storage=t,this.crypto=n,this.transport=o,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&vt(e.logger),this.confirmation=l,this.pinStore=h??new Qt,this.chainRegistry=d,this.jsonRpc=new Ks(d,o),this.signInUseCase=new Fs(this.internalConfig,t,n,i,o,a,c),this.signOutUseCase=new Vs(this.internalConfig,t,c),this.migrateWalletUseCase=new zs(t,a),(m=a.setOnUnauthorized)==null||m.call(a,()=>this.forceLogout())}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){console.log("[CROSSx SDK] v1.2.3 초기화 중..."),this.confirmation.setMessages(St(this._config.locale));try{const s=Js();this.internalConfig.oauthServiceUrl=s.oauthServiceUrl,this.internalConfig.authApiUrl=s.authApiUrl,this.internalConfig.walletGatewayUrl=s.walletGatewayUrl,this.adapterConfig.gatewayUrl=s.walletGatewayUrl;const t=await this.signInUseCase.restoreSession();if(t!=null&&t.success){this.applyAuthResult(t);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(n){if(!(n instanceof x&&n.code===p.PIN_CANCELLED))throw n;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(t!=null&&t.success)}),t??null}catch(s){throw new x(p.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let s=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector();if(t===null)return{success:!1,error:"User cancelled login"};s={...e,provider:t}}try{const t=await this.signInUseCase.execute(s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(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 x&&t.code===p.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithJWT(e,s){if(this.ensureInitialized(),this.authenticated)throw new x(p.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,s);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(p.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(p.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(s){s instanceof x&&s.code===p.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof x?s:new x(p.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(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 x?e:new x(p.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof x?s:new x(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(St(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new x(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const s=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}await this.ensurePinSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:s.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof x&&s.code===p.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(p.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(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 x(p.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(s,i.signature,n.address),{chainId:e,signature:i.signature,message:s,address:n.address}}catch(i){throw i instanceof x?i:new x(p.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,i)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(p.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(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 x(p.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const i=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,a,n.address)});return re.validateSignatureFormat(i.signature),{chainId:e,signature:i.signature,address:n.address}}catch(i){throw i instanceof x?i:new x(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 x(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=Xe(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(p.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return re.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(p.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new x(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=Xe(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:o.symbol,nativeDecimals:o.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(p.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(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??Xs,o=Qs,i=t.timeoutMs??It,a=Date.now()+i;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,s);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,o)}throw new x(p.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var E,y;const{intervalMs:n,timeoutMs:o,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=n??((E=this._config.receiptPolling)==null?void 0:E.intervalMs)??Zs,l=o??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??It,d=Xe(e),h=s.from??"";let m,g;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(S=>{m=S;const O=BigInt(S.gasUsed)*BigInt(S.effectiveGasPrice),B=s.value?BigInt(s.value):0n,v=re.formatTxAmount(s.value,d.symbol,d.decimals),P=re.formatTxAmount("0x"+O.toString(16),d.symbol,d.decimals),N=re.formatTxAmount("0x"+(B+O).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:S.from,to:S.to??s.to,amount:v,fees:P,total:N,nativeSymbol:d.symbol,status:S.status==="0x1"?"success":"reverted"}}).catch(S=>(g=S instanceof Error?S:new Error(String(S)),{chainId:e,txHash:a,from:h,to:s.to,amount:re.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:h,to:s.to},w),g)throw g;return{chainId:e,txHash:a,receipt:m}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new x(p.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,s),this.pinStore.set(s),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof x?n:new x(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 x(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 x(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 x(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 x(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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(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 x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(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(kt),n=s/t,i=(s%t).toString().padStart(kt,"0").replace(/0+$/,"").slice(0,At);return i?`${n}.${i}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Zt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(n){if(n instanceof x)throw n;const o=n instanceof Error?n.message:String(n);throw new x(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,At).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,n=0,o=5,i=null;for(;;){n++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${n}/${o})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:t,attemptCount:n>1?n-1:void 0,maxAttempts:o});if(l===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${l.length}자리) — verify-recovery-pin API 호출`),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyRecoveryPin)==null?void 0:c.call(a,l,e));if(!d){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const h=d.pinStatus;if(o=h.maxAttempts,n=o-h.remainingAttempts,h.remainingAttempts===0&&h.lockExpiresAt){const m=h.lockExpiresAt*1e3,g=Math.max(1,Math.round((m-Date.now())/1e3)),w=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${g}초, 메시지: ${w}`),await this.confirmation.showRecoveryPinLockedPrompt(g,w),n=0,t="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${n}/${o})`),t="Incorrect PIN."}catch(d){if(!(d instanceof x))throw d;if(d.code===p.MIGRATION_PIN_LOCKED){const h=d.details;if(o=(h==null?void 0:h.maxAttempts)??5,(h==null?void 0:h.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const m=((h==null?void 0:h.lockExpiresAt)??0)*1e3,g=Math.max(1,Math.round((m-Date.now())/1e3)),w=g<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${g}초`),await this.confirmation.showRecoveryPinLockedPrompt(g,w),n=0,t="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",d),d}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const l=await this.migrateWalletUseCase.execute(i,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof x&&l.code===p.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),n=e.nonce===void 0||e.nonce===null,o=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!o&&!i&&!a)return e;const c={...e};if(n){const l=c.from??this.address;if(l){u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)}}if(o&&(u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=Et;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=er,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=Et,u.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 x(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 x(p.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==o)throw new x(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 x(p.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Tt)throw new x(p.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${Tt} 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 x(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new x(p.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,s);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(p.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var 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&&(u.warn("[CROSSx] 인증 만료(Gateway -10002) — 강제 로그아웃"),this.clearAuthState())}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new x(p.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const s=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!s)throw new x(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(s),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,s){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let t,n;this._verifyPinMutex=new Promise((o,i)=>{t=o,n=i});try{if(typeof this.walletProvider.verifyPin!="function"){const i=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s});if(!i)throw new x(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(i),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),t();return}const o=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:s,onSubmit:async i=>{var a;this.pinStore.set(i);try{return await this.walletProvider.verifyPin(i)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:"Incorrect PIN. Please try again."})}catch(c){if(this.pinStore.clear(),c instanceof x){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 x(p.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(o),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),t()}catch(o){throw n(o),o}finally{this._verifyPinMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const o=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=o.address,this.activeWalletIndex=o.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:o.address,index:o.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){let s,t;try{return await e()}catch(n){if(n instanceof x)if(n.code===p.PIN_WRONG)s="Incorrect PIN. Please enter your current PIN.";else if(n.code===p.PIN_INVALID)s=n.message;else if(n.code===p.PIN_LOCKED){const o=n.details;t=o==null?void 0:o.lockExpiresAt,s="Too many failed attempts. Your account is temporarily locked."}else throw n;else throw n}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",s),this.pinStore.clear(),await this.ensureVerifiedPin(s,t),t=void 0;try{return await e()}catch(n){if(n instanceof x){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 x(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 x(p.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(p.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),vt(null)}};re.OFFCHAIN_CHAIN_ID="0";let qe=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 u.error("Storage set error:",t),t}}async get(e){try{const s=localStorage.getItem(this.prefix+e);return s?JSON.parse(s):null}catch(s){return u.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw u.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw u.error("Storage clear error:",e),e}}}const nr="crossx-sdk",or=1,Ie="data",Be="keys",Pt="aes-primary",ir=12;class Rt{constructor(){this.db=null,this.cryptoKey=null,this.initPromise=null}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(){return new Promise((e,s)=>{const t=indexedDB.open(nr,or);t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Ie)||n.createObjectStore(Ie),n.objectStoreNames.contains(Be)||n.createObjectStore(Be)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>n(i.error)})}idbPut(e,s,t){return new Promise((n,o)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>n(),a.onerror=()=>o(a.error)})}idbDelete(e,s){return new Promise((t,n)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>n(i.error)})}idbClear(e){return new Promise((s,t)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).clear();o.onsuccess=()=>s(),o.onerror=()=>t(o.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Be,Pt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Be,Pt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(ir);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(Ie,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Ie,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return u.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Ie,e)}catch(s){throw u.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Ie)}catch(e){throw u.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 ut(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function _e(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=ut(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 es(r){if(typeof r!="function"||typeof r.create!="function")throw new Error("Hash must wrapped by utils.createHasher");_e(r.outputLen),_e(r.blockLen)}function Ae(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 ts(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 ar(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function ke(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function Qe(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function de(r,e){return r<<32-e|r>>>e}const cr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function lr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function dr(r){for(let e=0;e<r.length;e++)r[e]=lr(r[e]);return r}const Nt=cr?r=>r:dr,ss=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",ur=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Me(r){if(z(r),ss)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=ur[r[s]];return e}const he={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ct(r){if(r>=he._0&&r<=he._9)return r-he._0;if(r>=he.A&&r<=he.F)return r-(he.A-10);if(r>=he.a&&r<=he.f)return r-(he.a-10)}function Ve(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);if(ss)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=Ct(r.charCodeAt(o)),a=Ct(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 ye(...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 rs(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 ns(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 hr=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function pr(r,e,s){return r&e^~r&s}function fr(r,e,s){return r&e^r&s^e&s}class _r{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=Qe(this.buffer)}update(e){Ae(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=Qe(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){Ae(this),ts(e,this),this.finished=!0;const{buffer:s,view:t,blockLen:n,isLE:o}=this;let{pos:i}=this;s[i++]=128,ke(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=Qe(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,d[h],o)}digest(){const{buffer:e,outputLen:s}=this;this.digestInto(e);const t=e.slice(0,s);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:s,buffer:t,length:n,finished:o,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=o,e.length=n,e.pos=a,n%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const xe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ue=BigInt(2**32-1),Ot=BigInt(32);function xr(r,e=!1){return e?{h:Number(r&Ue),l:Number(r>>Ot&Ue)}:{h:Number(r>>Ot&Ue)|0,l:Number(r&Ue)|0}}function gr(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}=xr(r[o],e);[t[o],n[o]]=[i,a]}return[t,n]}const mr=(r,e,s)=>r<<s|e>>>32-s,wr=(r,e,s)=>e<<s|r>>>32-s,yr=(r,e,s)=>e<<s-32|r>>>64-s,br=(r,e,s)=>r<<s-32|e>>>64-s,vr=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]),ge=new Uint32Array(64);class Sr extends _r{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)ge[h]=e.getUint32(s,!1);for(let h=16;h<64;h++){const m=ge[h-15],g=ge[h-2],w=de(m,7)^de(m,18)^m>>>3,E=de(g,17)^de(g,19)^g>>>10;ge[h]=E+ge[h-7]+w+ge[h-16]|0}let{A:t,B:n,C:o,D:i,E:a,F:c,G:l,H:d}=this;for(let h=0;h<64;h++){const m=de(a,6)^de(a,11)^de(a,25),g=d+m+pr(a,c,l)+vr[h]+ge[h]|0,E=(de(t,2)^de(t,13)^de(t,22))+fr(t,n,o)|0;d=l,l=c,c=a,a=i+g|0,i=o,o=n,n=t,t=g+E|0}t=t+this.A|0,n=n+this.B|0,o=o+this.C|0,i=i+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,o,i,a,c,l,d)}roundClean(){ke(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),ke(this.buffer)}}class Ir extends Sr{constructor(){super(32);I(this,"A",xe[0]|0);I(this,"B",xe[1]|0);I(this,"C",xe[2]|0);I(this,"D",xe[3]|0);I(this,"E",xe[4]|0);I(this,"F",xe[5]|0);I(this,"G",xe[6]|0);I(this,"H",xe[7]|0)}}const Er=rs(()=>new Ir,hr(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ht=BigInt(0),at=BigInt(1);function ze(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function os(r){if(typeof r=="bigint"){if(!Ge(r))throw new Error("positive bigint expected, got "+r)}else _e(r);return r}function He(r){const e=os(r).toString(16);return e.length&1?"0"+e:e}function is(r){if(typeof r!="string")throw new Error("hex string expected, got "+typeof r);return r===""?ht:BigInt("0x"+r)}function Ye(r){return is(Me(r))}function as(r){return is(Me(Tr(z(r)).reverse()))}function pt(r,e){_e(e),r=os(r);const s=Ve(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function cs(r,e){return pt(r,e).reverse()}function Tr(r){return Uint8Array.from(r)}const Ge=r=>typeof r=="bigint"&&ht<=r;function Ar(r,e,s){return Ge(r)&&Ge(e)&&Ge(s)&&e<=r&&r<s}function kr(r,e,s,t){if(!Ar(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Pr(r){let e;for(e=0;r>ht;r>>=at,e+=1);return e}const ft=r=>(at<<BigInt(r))-at;function Rr(r,e,s){if(_e(r,"hashLen"),_e(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),o=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const h=()=>{c.fill(1),l.fill(0),d=0},m=(...y)=>s(l,ye(c,...y)),g=(y=n)=>{l=m(o,y),c=m(),y.length!==0&&(l=m(i,y),c=m())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const S=[];for(;y<e;){c=m();const O=c.slice();S.push(O),y+=c.length}return ye(...S)};return(y,S)=>{h(),g(y);let O;for(;!(O=S(w()));)g();return h(),O}}function _t(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 Lt(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),ve=BigInt(2),ls=BigInt(3),ds=BigInt(4),us=BigInt(5),Nr=BigInt(7),hs=BigInt(8),Cr=BigInt(9),ps=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 Dt(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 xt(r,e,s){if(!r.eql(r.sqr(e),s))throw new Error("Cannot find square root")}function fs(r,e){const s=(r.ORDER+ee)/ds,t=r.pow(e,s);return xt(r,t,e),t}function Or(r,e){const s=(r.ORDER-us)/hs,t=r.mul(e,ve),n=r.pow(t,s),o=r.mul(e,n),i=r.mul(r.mul(o,ve),n),a=r.mul(o,r.sub(i,r.ONE));return xt(r,a,e),a}function Lr(r){const e=Je(r),s=_s(r),t=s(e,e.neg(e.ONE)),n=s(e,t),o=s(e,e.neg(t)),i=(r+Nr)/ps;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const h=a.mul(l,n),m=a.mul(l,o),g=a.eql(a.sqr(d),c),w=a.eql(a.sqr(h),c);l=a.cmov(l,d,g),d=a.cmov(m,h,w);const E=a.eql(a.sqr(d),c),y=a.cmov(l,d,E);return xt(a,y,c),y}}function _s(r){if(r<ls)throw new Error("sqrt is not defined for small field");let e=r-ee,s=0;for(;e%ve===ne;)e/=ve,s++;let t=ve;const n=Je(r);for(;Mt(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return fs;let o=n.pow(t,e);const i=(e+ee)/ve;return function(c,l){if(c.is0(l))return l;if(Mt(c,l)!==1)throw new Error("Cannot find square root");let d=s,h=c.mul(c.ONE,o),m=c.pow(l,e),g=c.pow(l,i);for(;!c.eql(m,c.ONE);){if(c.is0(m))return c.ZERO;let w=1,E=c.sqr(m);for(;!c.eql(E,c.ONE);)if(w++,E=c.sqr(E),w===d)throw new Error("Cannot find square root");const y=ee<<BigInt(d-w-1),S=c.pow(h,y);d=w,h=c.sqr(S),m=c.mul(m,h),g=c.mul(g,S)}return g}}function Dr(r){return r%ds===ls?fs:r%hs===us?Or:r%ps===Cr?Lr(r):_s(r)}const Mr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $r(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Mr.reduce((t,n)=>(t[n]="function",t),e);return _t(r,s),r}function Br(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 xs(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 Mt(r,e){const s=(r.ORDER-ee)/ve,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 Ur(r,e){e!==void 0&&_e(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Hr{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}=Ur(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 Br(this,e,s)}div(e,s){return le(e*Dt(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 Dt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Dr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?cs(e,this.BYTES):pt(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?as(e):Ye(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 xs(this,e)}cmov(e,s,t){return t?s:e}}function Je(r,e={}){return new Hr(r,e)}function gs(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 ms(r){const e=gs(r);return e+Math.ceil(e/2)}function Fr(r,e,s=!1){z(r);const t=r.length,n=gs(e),o=ms(e);if(t<16||t<o||t>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+t);const i=s?as(r):Ye(r),a=le(i,e-ee)+ee;return s?cs(a,n):pt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pe=BigInt(0),Se=BigInt(1);function Ke(r,e){const s=e.negate();return r?s:e}function $t(r,e){const s=xs(r.Fp,e.map(t=>t.Z));return e.map((t,n)=>r.fromAffine(t.toAffine(s[n])))}function ws(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function et(r,e){ws(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),n=2**r,o=ft(r),i=BigInt(r);return{windows:s,windowSize:t,mask:o,maxNumber:n,shiftBy:i}}function Bt(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+=Se);const l=e*t,d=l+Math.abs(a)-1,h=a===0,m=a<0,g=e%2!==0;return{nextN:c,offset:d,isZero:h,isNeg:m,isNegF:g,offsetF:l}}const tt=new WeakMap,ys=new WeakMap;function st(r){return ys.get(r)||1}function Ut(r){if(r!==Pe)throw new Error("invalid wNAF")}class Gr{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>Pe;)s&Se&&(t=t.add(n)),n=n.double(),s>>=Se;return t}precomputeWindow(e,s){const{windows:t,windowSize:n}=et(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=et(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:h,isNegF:m,offsetF:g}=Bt(t,a,i);t=c,d?o=o.add(Ke(m,s[g])):n=n.add(Ke(h,s[l]))}return Ut(t),{p:n,f:o}}wNAFUnsafe(e,s,t,n=this.ZERO){const o=et(e,this.bits);for(let i=0;i<o.windows&&t!==Pe;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Bt(t,i,o);if(t=a,!l){const h=s[c];n=n.add(d?h.negate():h)}}return Ut(t),n}getPrecomputes(e,s,t){let n=tt.get(s);return n||(n=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(n=t(n)),tt.set(s,n))),n}cached(e,s,t){const n=st(e);return this.wNAF(n,this.getPrecomputes(n,e,t),s)}unsafe(e,s,t,n){const o=st(e);return o===1?this._unsafeLadder(e,s,n):this.wNAFUnsafe(o,this.getPrecomputes(o,e,t),s,n)}createCache(e,s){ws(s,this.bits),ys.set(e,s),tt.delete(e)}hasCache(e){return st(e)!==1}}function Wr(r,e,s,t){let n=e,o=r.ZERO,i=r.ZERO;for(;s>Pe||t>Pe;)s&Se&&(o=o.add(n)),t&Se&&(i=i.add(n)),n=n.double(),s>>=Se,t>>=Se;return{p1:o,p2:i}}function Ht(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return $r(e),e}else return Je(r,{isLE:s})}function qr(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>Pe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=Ht(e.p,s.Fp,t),o=Ht(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 Vr(r,e){return function(t){const n=r(t);return{secretKey:n,publicKey:e(n)}}}class bs{constructor(e,s){I(this,"oHash");I(this,"iHash");I(this,"blockLen");I(this,"outputLen");I(this,"finished",!1);I(this,"destroyed",!1);if(es(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),ke(n)}update(e){return Ae(this),this.iHash.update(e),this}digestInto(e){Ae(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 vs=(r,e,s)=>new bs(r,e).update(s).digest();vs.create=(r,e)=>new bs(r,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ft=(r,e)=>(r+(r>=0?e:-e)/Ss)/e;function zr(r,e,s){const[[t,n],[o,i]]=e,a=Ft(i*r,s),c=Ft(-n*r,s);let l=r-a*t-c*o,d=-a*n-c*i;const h=l<pe,m=d<pe;h&&(l=-l),m&&(d=-d);const g=ft(Math.ceil(Pr(s)/2))+Te;if(l<pe||l>=g||d<pe||d>=g)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:h,k1:l,k2neg:m,k2:d}}function ct(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function rt(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return ze(s.lowS,"lowS"),ze(s.prehash,"prehash"),s.format!==void 0&&ct(s.format),s}class Kr extends Error{constructor(e=""){super(e)}}const me={Err:Kr,_tlv:{encode:(r,e)=>{const{Err:s}=me;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=He(t);if(n.length/2&128)throw new s("tlv.encode: long form length too big");const o=t>127?He(n.length/2|128):"";return He(r)+o+n+e},decode(r,e){const{Err:s}=me;let t=0;if(r<0||r>256)throw new s("tlv.encode: wrong tag");if(e.length<2||e[t++]!==r)throw new s("tlv.decode: wrong tlv");const n=e[t++],o=!!(n&128);let i=0;if(!o)i=n;else{const c=n&127;if(!c)throw new s("tlv.decode(long): indefinite length not supported");if(c>4)throw new s("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new s("tlv.decode: length bytes not complete");if(l[0]===0)throw new s("tlv.decode(long): zero leftmost byte");for(const d of l)i=i<<8|d;if(t+=c,i<128)throw new s("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+i);if(a.length!==i)throw new s("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+i)}}},_int:{encode(r){const{Err:e}=me;if(r<pe)throw new e("integer: negative integers are not allowed");let s=He(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}=me;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 Ye(r)}},toSig(r){const{Err:e,_int:s,_tlv:t}=me,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:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:s.decode(a),s:s.decode(l)}},hexFromSig(r){const{_tlv:e,_int:s}=me,t=e.encode(2,s.encode(r.r)),n=e.encode(2,s.encode(r.s)),o=t+n;return e.encode(48,o)}},pe=BigInt(0),Te=BigInt(1),Ss=BigInt(2),Fe=BigInt(3),jr=BigInt(4);function Yr(r,e={}){const s=qr("weierstrass",r,e),{Fp:t,Fn:n}=s;let o=s.CURVE;const{h:i,n:a}=o;_t(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=Es(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(R,f,_){const{x:b,y:A}=f.toAffine(),L=t.toBytes(b);if(ze(_,"isCompressed"),_){d();const C=!t.isOdd(A);return ye(Is(C),L)}else return ye(Uint8Array.of(4),L,t.toBytes(A))}function m(R){z(R,void 0,"Point");const{publicKey:f,publicKeyUncompressed:_}=l,b=R.length,A=R[0],L=R.subarray(1);if(b===f&&(A===2||A===3)){const C=t.fromBytes(L);if(!t.isValid(C))throw new Error("bad point: is not on curve, wrong x");const M=E(C);let T;try{T=t.sqrt(M)}catch(J){const V=J instanceof Error?": "+J.message:"";throw new Error("bad point: is not on curve, sqrt error"+V)}d();const $=t.isOdd(T);return(A&1)===1!==$&&(T=t.neg(T)),{x:C,y:T}}else if(b===_&&A===4){const C=t.BYTES,M=t.fromBytes(L.subarray(0,C)),T=t.fromBytes(L.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 ${b}, expected compressed=${f} or uncompressed=${_}`)}const g=e.toBytes||h,w=e.fromBytes||m;function E(R){const f=t.sqr(R),_=t.mul(f,R);return t.add(t.add(_,t.mul(R,o.a)),o.b)}function y(R,f){const _=t.sqr(f),b=E(R);return t.eql(_,b)}if(!y(o.Gx,o.Gy))throw new Error("bad curve params: generator point");const S=t.mul(t.pow(o.a,Fe),jr),O=t.mul(t.sqr(o.b),BigInt(27));if(t.is0(t.add(S,O)))throw new Error("bad curve params: a or b");function B(R,f,_=!1){if(!t.isValid(f)||_&&t.is0(f))throw new Error(`bad point coordinate ${R}`);return f}function v(R){if(!(R instanceof W))throw new Error("Weierstrass Point expected")}function P(R){if(!c||!c.basises)throw new Error("no endo");return zr(R,c.basises,n.ORDER)}const N=Lt((R,f)=>{const{X:_,Y:b,Z:A}=R;if(t.eql(A,t.ONE))return{x:_,y:b};const L=R.is0();f==null&&(f=L?t.ONE:t.inv(A));const C=t.mul(_,f),M=t.mul(b,f),T=t.mul(A,f);if(L)return{x:t.ZERO,y:t.ZERO};if(!t.eql(T,t.ONE))throw new Error("invZ was invalid");return{x:C,y:M}}),G=Lt(R=>{if(R.is0()){if(e.allowInfinityPoint&&!t.is0(R.Y))return;throw new Error("bad point: ZERO")}const{x:f,y:_}=R.toAffine();if(!t.isValid(f)||!t.isValid(_))throw new Error("bad point: x or y not field elements");if(!y(f,_))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function K(R,f,_,b,A){return _=new W(t.mul(_.X,R),_.Y,_.Z),f=Ke(b,f),_=Ke(A,_),f.add(_)}const k=class k{constructor(f,_,b){I(this,"X");I(this,"Y");I(this,"Z");this.X=B("x",f),this.Y=B("y",_,!0),this.Z=B("z",b),Object.freeze(this)}static CURVE(){return o}static fromAffine(f){const{x:_,y:b}=f||{};if(!f||!t.isValid(_)||!t.isValid(b))throw new Error("invalid affine point");if(f instanceof k)throw new Error("projective point not allowed");return t.is0(_)&&t.is0(b)?k.ZERO:new k(_,b,t.ONE)}static fromBytes(f){const _=k.fromAffine(w(z(f,void 0,"point")));return _.assertValidity(),_}static fromHex(f){return k.fromBytes(Ve(f))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(f=8,_=!0){return D.createCache(this,f),_||this.multiply(Fe),this}assertValidity(){G(this)}hasEvenY(){const{y:f}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(f)}equals(f){v(f);const{X:_,Y:b,Z:A}=this,{X:L,Y:C,Z:M}=f,T=t.eql(t.mul(_,M),t.mul(L,A)),$=t.eql(t.mul(b,M),t.mul(C,A));return T&&$}negate(){return new k(this.X,t.neg(this.Y),this.Z)}double(){const{a:f,b:_}=o,b=t.mul(_,Fe),{X:A,Y:L,Z:C}=this;let M=t.ZERO,T=t.ZERO,$=t.ZERO,F=t.mul(A,A),J=t.mul(L,L),V=t.mul(C,C),H=t.mul(A,L);return H=t.add(H,H),$=t.mul(A,C),$=t.add($,$),M=t.mul(f,$),T=t.mul(b,V),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(b,$),V=t.mul(f,V),H=t.sub(F,V),H=t.mul(f,H),H=t.add(H,$),$=t.add(F,F),F=t.add($,F),F=t.add(F,V),F=t.mul(F,H),T=t.add(T,F),V=t.mul(L,C),V=t.add(V,V),F=t.mul(V,H),M=t.sub(M,F),$=t.mul(V,J),$=t.add($,$),$=t.add($,$),new k(M,T,$)}add(f){v(f);const{X:_,Y:b,Z:A}=this,{X:L,Y:C,Z:M}=f;let T=t.ZERO,$=t.ZERO,F=t.ZERO;const J=o.a,V=t.mul(o.b,Fe);let H=t.mul(_,L),Z=t.mul(b,C),X=t.mul(A,M),oe=t.add(_,b),j=t.add(L,C);oe=t.mul(oe,j),j=t.add(H,Z),oe=t.sub(oe,j),j=t.add(_,A);let Q=t.add(L,M);return j=t.mul(j,Q),Q=t.add(H,X),j=t.sub(j,Q),Q=t.add(b,A),T=t.add(C,M),Q=t.mul(Q,T),T=t.add(Z,X),Q=t.sub(Q,T),F=t.mul(J,j),T=t.mul(V,X),F=t.add(T,F),T=t.sub(Z,F),F=t.add(Z,F),$=t.mul(T,F),Z=t.add(H,H),Z=t.add(Z,H),X=t.mul(J,X),j=t.mul(V,j),Z=t.add(Z,X),X=t.sub(H,X),X=t.mul(J,X),j=t.add(j,X),H=t.mul(Z,j),$=t.add($,H),H=t.mul(Q,j),T=t.mul(oe,T),T=t.sub(T,H),H=t.mul(oe,Z),F=t.mul(Q,F),F=t.add(F,H),new k(T,$,F)}subtract(f){return this.add(f.negate())}is0(){return this.equals(k.ZERO)}multiply(f){const{endo:_}=e;if(!n.isValidNot0(f))throw new Error("invalid scalar: out of range");let b,A;const L=C=>D.cached(this,C,M=>$t(k,M));if(_){const{k1neg:C,k1:M,k2neg:T,k2:$}=P(f),{p:F,f:J}=L(M),{p:V,f:H}=L($);A=J.add(H),b=K(_.beta,F,V,C,T)}else{const{p:C,f:M}=L(f);b=C,A=M}return $t(k,[b,A])[0]}multiplyUnsafe(f){const{endo:_}=e,b=this;if(!n.isValid(f))throw new Error("invalid scalar: out of range");if(f===pe||b.is0())return k.ZERO;if(f===Te)return b;if(D.hasCache(this))return this.multiply(f);if(_){const{k1neg:A,k1:L,k2neg:C,k2:M}=P(f),{p1:T,p2:$}=Wr(k,b,L,M);return K(_.beta,T,$,A,C)}else return D.unsafe(b,f)}toAffine(f){return N(this,f)}isTorsionFree(){const{isTorsionFree:f}=e;return i===Te?!0:f?f(k,this):D.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:f}=e;return i===Te?this:f?f(k,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(f=!0){return ze(f,"isCompressed"),this.assertValidity(),g(k,this,f)}toHex(f=!0){return Me(this.toBytes(f))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};I(k,"BASE",new k(o.Gx,o.Gy,t.ONE)),I(k,"ZERO",new k(t.ZERO,t.ONE,t.ZERO)),I(k,"Fp",t),I(k,"Fn",n);let W=k;const q=n.BITS,D=new Gr(W,e.endo?Math.ceil(q/2):q);return W.BASE.precompute(8),W}function Is(r){return Uint8Array.of(r?2:3)}function Es(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Jr(r,e={}){const{Fn:s}=r,t=e.randomBytes||ns,n=Object.assign(Es(r.Fp,s),{seed:ms(s.ORDER)});function o(g){try{const w=s.fromBytes(g);return s.isValidNot0(w)}catch{return!1}}function i(g,w){const{publicKey:E,publicKeyUncompressed:y}=n;try{const S=g.length;return w===!0&&S!==E||w===!1&&S!==y?!1:!!r.fromBytes(g)}catch{return!1}}function a(g=t(n.seed)){return Fr(z(g,n.seed,"seed"),s.ORDER)}function c(g,w=!0){return r.BASE.multiply(s.fromBytes(g)).toBytes(w)}function l(g){const{secretKey:w,publicKey:E,publicKeyUncompressed:y}=n;if(!ut(g)||"_lengths"in s&&s._lengths||w===E)return;const S=z(g,void 0,"key").length;return S===E||S===y}function d(g,w,E=!0){if(l(g)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(g);return r.fromBytes(w).multiply(y).toBytes(E)}const h={isValidSecretKey:o,isValidPublicKey:i,randomSecretKey:a},m=Vr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:m,Point:r,utils:h,lengths:n})}function Zr(r,e,s={}){es(e),_t(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||ns,n=s.hmac||((f,_)=>vs(e,f,_)),{Fp:o,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:g}=Jr(r,s),w={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},E=a*Ss<o.ORDER;function y(f){const _=a>>Te;return f>_}function S(f,_){if(!i.isValidNot0(_))throw new Error(`invalid signature ${f}: out of range 1..Point.Fn.ORDER`);return _}function O(){if(E)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function B(f,_){ct(_);const b=g.signature,A=_==="compact"?b:_==="recovered"?b+1:void 0;return z(f,A)}class v{constructor(_,b,A){I(this,"r");I(this,"s");I(this,"recovery");if(this.r=S("r",_),this.s=S("s",b),A!=null){if(O(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(_,b=w.format){B(_,b);let A;if(b==="der"){const{r:T,s:$}=me.toSig(z(_));return new v(T,$)}b==="recovered"&&(A=_[0],b="compact",_=_.subarray(1));const L=g.signature/2,C=_.subarray(0,L),M=_.subarray(L,L*2);return new v(i.fromBytes(C),i.fromBytes(M),A)}static fromHex(_,b){return this.fromBytes(Ve(_),b)}assertRecovery(){const{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new v(this.r,this.s,_)}recoverPublicKey(_){const{r:b,s:A}=this,L=this.assertRecovery(),C=L===2||L===3?b+a:b;if(!o.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=o.toBytes(C),T=r.fromBytes(ye(Is((L&1)===0),M)),$=i.inv(C),F=N(z(_,void 0,"msgHash")),J=i.create(-F*$),V=i.create(A*$),H=r.BASE.multiplyUnsafe(J).add(T.multiplyUnsafe(V));if(H.is0())throw new Error("invalid recovery: point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(_=w.format){if(ct(_),_==="der")return Ve(me.hexFromSig(this));const{r:b,s:A}=this,L=i.toBytes(b),C=i.toBytes(A);return _==="recovered"?(O(),ye(Uint8Array.of(this.assertRecovery()),L,C)):ye(L,C)}toHex(_){return Me(this.toBytes(_))}}const P=s.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const b=Ye(_),A=_.length*8-c;return A>0?b>>BigInt(A):b},N=s.bits2int_modN||function(_){return i.create(P(_))},G=ft(c);function K(f){return kr("num < 2^"+c,f,pe,G),i.toBytes(f)}function W(f,_){return z(f,void 0,"message"),_?z(e(f),void 0,"prehashed message"):f}function q(f,_,b){const{lowS:A,prehash:L,extraEntropy:C}=rt(b,w);f=W(f,L);const M=N(f),T=i.fromBytes(_);if(!i.isValidNot0(T))throw new Error("invalid private key");const $=[K(T),K(M)];if(C!=null&&C!==!1){const H=C===!0?t(g.secretKey):C;$.push(z(H,void 0,"extraEntropy"))}const F=ye(...$),J=M;function V(H){const Z=P(H);if(!i.isValidNot0(Z))return;const X=i.inv(Z),oe=r.BASE.multiply(Z).toAffine(),j=i.create(oe.x);if(j===pe)return;const Q=i.create(X*i.create(J+j*T));if(Q===pe)return;let yt=(oe.x===j?0:2)|Number(oe.y&Te),bt=Q;return A&&y(Q)&&(bt=i.neg(Q),yt^=1),new v(j,bt,E?void 0:yt)}return{seed:F,k2sig:V}}function D(f,_,b={}){const{seed:A,k2sig:L}=q(f,_,b);return Rr(e.outputLen,i.BYTES,n)(A,L).toBytes(b.format)}function k(f,_,b,A={}){const{lowS:L,prehash:C,format:M}=rt(A,w);if(b=z(b,void 0,"publicKey"),_=W(_,C),!ut(f)){const T=f instanceof v?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+T)}B(f,M);try{const T=v.fromBytes(f,M),$=r.fromBytes(b);if(L&&T.hasHighS())return!1;const{r:F,s:J}=T,V=N(_),H=i.inv(J),Z=i.create(V*H),X=i.create(F*H),oe=r.BASE.multiplyUnsafe(Z).add($.multiplyUnsafe(X));return oe.is0()?!1:i.create(oe.x)===F}catch{return!1}}function R(f,_,b={}){const{prehash:A}=rt(b,w);return _=W(_,A),v.fromBytes(f,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:h,utils:m,lengths:g,Point:r,sign:D,verify:k,recoverPublicKey:R,Signature:v,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Xr={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Gt=BigInt(2);function Qr(r){const e=gt.p,s=BigInt(3),t=BigInt(6),n=BigInt(11),o=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,h=ae(d,s,e)*d%e,m=ae(h,s,e)*d%e,g=ae(m,Gt,e)*l%e,w=ae(g,n,e)*g%e,E=ae(w,o,e)*w%e,y=ae(E,a,e)*E%e,S=ae(y,c,e)*y%e,O=ae(S,a,e)*E%e,B=ae(O,s,e)*d%e,v=ae(B,i,e)*w%e,P=ae(v,t,e)*l%e,N=ae(P,Gt,e);if(!lt.eql(lt.sqr(N),r))throw new Error("Cannot find square root");return N}const lt=Je(gt.p,{sqrt:Qr}),en=Yr(gt,{Fp:lt,endo:Xr}),tn=Zr(en,Er),sn=BigInt(0),Ce=BigInt(1),rn=BigInt(2),nn=BigInt(7),on=BigInt(256),an=BigInt(113),Ts=[],As=[],ks=[];for(let r=0,e=Ce,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],Ts.push(2*(5*t+s)),As.push((r+1)*(r+2)/2%64);let n=sn;for(let o=0;o<7;o++)e=(e<<Ce^(e>>nn)*an)%on,e&rn&&(n^=Ce<<(Ce<<BigInt(o))-Ce);ks.push(n)}const Ps=gr(ks,!0),cn=Ps[0],ln=Ps[1],Wt=(r,e,s)=>s>32?yr(r,e,s):mr(r,e,s),qt=(r,e,s)=>s>32?br(r,e,s):wr(r,e,s);function dn(r,e=24){const s=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let i=0;i<10;i++)s[i]=r[i]^r[i+10]^r[i+20]^r[i+30]^r[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=s[c],d=s[c+1],h=Wt(l,d,1)^s[a],m=qt(l,d,1)^s[a+1];for(let g=0;g<50;g+=10)r[i+g]^=h,r[i+g+1]^=m}let n=r[2],o=r[3];for(let i=0;i<24;i++){const a=As[i],c=Wt(n,o,a),l=qt(n,o,a),d=Ts[i];n=r[d],o=r[d+1],r[d]=c,r[d+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)s[a]=r[i+a];for(let a=0;a<10;a++)r[i+a]^=~s[(a+2)%10]&s[(a+4)%10]}r[0]^=cn[t],r[1]^=ln[t]}ke(s)}class mt{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,_e(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ar(this.state)}clone(){return this._cloneInto()}keccak(){Nt(this.state32),dn(this.state32,this.rounds),Nt(this.state32),this.posOut=0,this.pos=0}update(e){Ae(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){Ae(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 _e(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ts(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,ke(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:n,rounds:o,enableXOF:i}=this;return e||(e=new mt(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 un=(r,e,s,t={})=>rs(()=>new mt(e,r,s),t),Vt=un(1,136,32);class hn{async verifyJWT(e,s){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const n=Math.floor(Date.now()/1e3);return t.exp&&t.exp<n?(u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ds.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=Vt(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),d=c.slice(32,64),h=c[64],m=h>=27?h-27:h,E=new tn.Signature(zt(l),zt(d)).addRecoveryBit(m).recoverPublicKey(i).toBytes(!1).slice(1),y=Vt(E);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 zt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const fn=3e4;class _n{async request(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)}}}class we{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=we.parseJwtPayload(e),n=t.nonce,o=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:o,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),o.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n==="")throw u.error("[CROSSx] nonce claim 누락 — JWT payload 전체 키 목록:",Object.keys(t)),u.error("[CROSSx] 원인 추정: OAuth 서버가 Google/Apple 인증 요청에 nonce 파라미터를 포함하지 않았을 수 있습니다.","서버 로그에서 /auth/google, /auth/apple 요청 URL에 nonce 쿼리가 있는지 확인하세요."),new Error("ID Token에 nonce claim이 없습니다 — OAuth 서버 설정을 확인해 주세요");if(o.includes("appleid.apple.com")){const i=await we.sha256Hex(s);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:i.length,receivedHashLength:n.length,match:n===i}),n!==i)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:s.length,receivedLength:n.length,match:n===s}),n!==s)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:o})}openAuth(e){return new Promise((s,t)=>{const n=Math.max(e.width??500,500),o=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-o)/2,c=we.generateRandom16Hex(),l=we.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",h=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const m=window.open(h,"CROSSx OAuth",`width=${n},height=${o},left=${i},top=${a}`);if(!m){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const g=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),v(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,E=30;let y=0,S=null;const O=()=>{clearInterval(B),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+E+"초간 대기합니다"),S=setTimeout(()=>{v(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},E*1e3)},B=setInterval(()=>{y++;try{m.closed&&(y<=w?O():(v(),t(new Error("로그인이 취소되었습니다"))))}catch{O()}},1e3),v=()=>{clearTimeout(g),clearInterval(B),S&&clearTimeout(S),window.removeEventListener("message",P)},P=N=>{var K,W,q,D,k;if(N.origin!==e.expectedOrigin)return;v(),u.log("[CROSSx] OAuth postMessage 수신 — status:",N.data.status);const G=N.data.state??((K=N.data.data)==null?void 0:K.state);if(!G||G!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(N.data.status==="success"){const R=(W=N.data.data)==null?void 0:W.idToken,f=(q=N.data.data)==null?void 0:q.accessToken,_=f??R;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!f,hasIdToken:!!R}),!_){u.error("[CROSSx] 토큰을 찾을 수 없음:",N.data),t(new Error("Token not found in response"));return}if(R){try{const b=we.parseJwtPayload(R);u.log("[CROSSx] idToken JWT payload 요약:",{iss:b.iss,sub:typeof b.sub=="string"?`${b.sub.slice(0,6)}...`:"(absent)",hasNonceClaim:"nonce"in b,nonceClaimType:typeof b.nonce,appleNonceSupported:b.nonce_supported??"(field absent)"})}catch{u.warn("[CROSSx] idToken JWT payload 파싱 실패 — 토큰 형식을 확인하세요")}we.verifyIdTokenNonce(R,l).then(()=>s(_)).catch(b=>{u.error("[CROSSx] nonce 검증 실패:",b),t(b instanceof Error?b:new Error("nonce verification failed"))})}else s(_)}else u.error("[CROSSx] OAuth 실패:",(D=N.data.data)==null?void 0:D.error),t(new Error(((k=N.data.data)==null?void 0:k.error)||"Authentication failed"))};window.addEventListener("message",P)})}}const Oe="crossx_wallet_data",Ee="crossx_mock_pin_hash";class xn{constructor(e,s){this.storage=e,this.pinStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Oe)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Oe);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(Oe,n);const o=(s=this.pinStore)==null?void 0:s.get();return o&&(await this.storage.set(Ee,o),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(p.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Oe);return s?[{address:s.address,index:0}]:[]}async getAddress(e,s){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,n=0,o,i){return u.log(`[Mock] signMessage chainId=${s} index=${n} uuid=${o} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,n=0,o,i){return u.log(`[Mock] signTypedData chainId=${s} index=${n} uuid=${o} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,n=0,o){u.log(`[Mock] signTransaction chainId=${s} index=${n} uuid=${o}:`,t);const i="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:s,signature:this.generateMockSignature(),txHash:i,format:"hex"}}async sendTransaction(e,s,t,n){return u.log(`[Mock] sendTransaction chainId=${s} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const s=await this.storage.get(Ee);return s&&s!==e?!1:(s||await this.storage.set(Ee,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,s){var o;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(p.PIN_WRONG,"Incorrect PIN.");const t=(o=this.pinStore)==null?void 0:o.get(),n=await this.storage.get(Ee);if(n&&t&&n!==t)throw new x(p.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ee,s),u.log("[Mock] changePin 완료")}async migrateWallet(e,s){var o;if(u.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new x(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 x(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(Oe,t);const n=(o=this.pinStore)==null?void 0:o.get();return n&&(await this.storage.set(Ee,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,s){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class 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 x(p.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const n=this.getAuthToken(),o=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${n}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:o,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const h=d.message||d.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:h,url:o,method:e,fullResponse:d});const m=Le.mapGatewayError(d.code,d.data),g=Le.getGatewayErrorMessage(d.code,h),w=d.data,E=m===p.PIN_LOCKED?Le.extractLockDetails(w):w??void 0,y=new x(m,g,E);throw y.gatewayCode=d.code,y.gatewayMessage=h,m===p.AUTH_NOT_AUTHENTICATED&&this._onUnauthorized&&(u.warn("[CROSSx] Gateway -10002 감지 — 강제 로그아웃 실행"),this._onUnauthorized()),y}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:o,method:e}),d.data??d}return d}catch(l){if(l instanceof x)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,h=d.message||d.data||"API 요청에 실패했습니다",m=d.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:m,message:h,url:o,method:e,status:(c=l.response)==null?void 0:c.status}),new x(p.UNKNOWN_ERROR,`Wallet Gateway 오류 (${m}): ${h}`)}throw l}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let s;if(this._walletStatusCache!==null?(s=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new x(p.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const o=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",o.address),{id:e,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,s){const t={password:this.requirePin(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new x(p.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new x(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 x(p.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const n={action:e,params:t},o=await this.request("POST","/mnemonic/prepare",n);return{uuid:o.uuid,expiresAt:o.expiresAt}}async signMessage(e,s,t,n,o,i){const a={message:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:c.signature,format:"hex"}}async signTypedData(e,s,t,n,o,i){const a={typedData:t,password:this.requirePin()};o&&(a.uuid=o),i&&(a.from=i);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,s,t,n,o){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};o&&(i.uuid=o);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,s,t,n){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(o.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,o)).txHash}}async migrateWallet(e,s){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={recoveryPin:e,sub:s,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:s,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPin(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).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 x(p.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const s=(e==null?void 0:e.lockStatus)??e,t=(s==null?void 0:s.lockExpiresAt)??(s==null?void 0:s.lock_expires_at);return t?{lockExpiresAt:t>1e10?t:t*1e3}:{}}static mapGatewayError(e,s){switch(e){case-10002:return p.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return p.UNKNOWN_ERROR;case-10006:return p.GATEWAY_INTERNAL_ERROR;case-10008:return p.GATEWAY_LOCK_CONFLICT;case-10010:return p.MIGRATION_FAILED;case-10012:return p.MIGRATION_BACKUP_EXISTS;case-10027:return p.MIGRATION_PIN_LOCKED;case-10022:return p.PROJECT_NOT_REGISTERED;case-10023:return p.PROJECT_ID_MISSING;case-10024:return p.ORIGIN_NOT_ALLOWED;case-10028:return p.PIN_WRONG;case-10029:return p.PIN_INVALID;case-10031:return p.PIN_LOCKED;case-10030:return p.WALLET_INCONSISTENT_STATE;case-10026:return p.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return p.PREPARE_FAILED;case-10016:return p.PREPARE_EXPIRED;case-10017:case-10018:return p.PREPARE_MISMATCH;default:return p.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,s){switch(e){case-10002:return"Session expired. Please sign in again.";case-10006:return"Internal server error. Please try again later.";case-10008:return"Another operation is in progress. Please try again later.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin is not in the allowed list. Register the current domain in the management console.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Invalid PIN format. Please enter a 6-digit numeric PIN.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";default:return`Request failed (${e}): ${s}`}}}class 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 x(De.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=De.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new x(p.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(je).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 Kt="__crossx-confirm-style",te="__crossx-confirm-overlay",gn={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 jt(r,e){const s=gn[r],t=e==null?void 0:e[r];return t?{...s,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:s}const mn=`
3
3
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
4
4
 
5
5
  #${te} {
@@ -557,6 +557,19 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
557
557
  filter: none !important;
558
558
  transform: none !important;
559
559
  }
560
+ .__crossx-recover-icon {
561
+ display: flex;
562
+ align-items: center;
563
+ justify-content: center;
564
+ flex-shrink: 0;
565
+ width: 40px;
566
+ height: 40px;
567
+ }
568
+ .__crossx-recover-icon svg {
569
+ width: 40px;
570
+ height: 40px;
571
+ display: block;
572
+ }
560
573
  .__crossx-recover-label {
561
574
  font-size: 18px;
562
575
  font-weight: 700;
@@ -815,7 +828,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
815
828
  .__crossx-approve-btn {
816
829
  width: 100%;
817
830
  padding: 16px;
818
- border: 1px solid rgba(18,18,18,0.05);
831
+ border: 1px solid var(--cx-border);
819
832
  border-radius: 12px;
820
833
  background: var(--cx-primary);
821
834
  color: var(--cx-on-primary);
@@ -868,7 +881,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
868
881
  .__crossx-confirm-btn {
869
882
  flex: 1;
870
883
  padding: 16px;
871
- border: 1px solid rgba(18,18,18,0.05);
884
+ border: 1px solid var(--cx-border);
872
885
  border-radius: 12px;
873
886
  background: var(--cx-primary);
874
887
  color: var(--cx-on-primary);
@@ -890,6 +903,52 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
890
903
  color: var(--cx-on-primary) !important;
891
904
  }
892
905
 
906
+ /* ── Sign/Send modals: max-height + sticky buttons ─────────── */
907
+ .__crossx-card--send-tx,
908
+ .__crossx-card--sign-tx,
909
+ .__crossx-card--sign-msg,
910
+ .__crossx-card--sign-typed {
911
+ display: flex;
912
+ flex-direction: column;
913
+ max-height: 90vh;
914
+ }
915
+ /* sign-tx: col-right-sign이 스크롤 담당, raw-tx는 자연 높이 */
916
+ .__crossx-card--sign-tx .__crossx-col-right-sign {
917
+ flex: 1;
918
+ min-height: 0;
919
+ overflow-y: auto;
920
+ }
921
+ .__crossx-card--sign-tx .__crossx-col-right-sign .__crossx-rows { flex-shrink: 0; }
922
+ .__crossx-card--sign-tx .__crossx-raw-tx { max-height: none; overflow-y: visible; }
923
+ .__crossx-card--send-tx .__crossx-body,
924
+ .__crossx-card--sign-tx .__crossx-body,
925
+ .__crossx-card--sign-msg .__crossx-body,
926
+ .__crossx-card--sign-typed .__crossx-body {
927
+ flex: 1;
928
+ min-height: 0;
929
+ display: flex;
930
+ flex-direction: column;
931
+ overflow: hidden;
932
+ }
933
+ .__crossx-card--send-tx .__crossx-body-cols,
934
+ .__crossx-card--sign-tx .__crossx-body-cols,
935
+ .__crossx-card--sign-msg .__crossx-body-cols,
936
+ .__crossx-card--sign-typed .__crossx-body-cols {
937
+ flex: 1;
938
+ min-height: 0;
939
+ overflow-y: auto;
940
+ }
941
+ .__crossx-card--send-tx .__crossx-btn-row,
942
+ .__crossx-card--sign-tx .__crossx-btn-row,
943
+ .__crossx-card--sign-msg .__crossx-btn-row,
944
+ .__crossx-card--sign-typed .__crossx-btn-row,
945
+ .__crossx-card--send-tx .__crossx-body > .__crossx-approve-btn,
946
+ .__crossx-card--sign-tx .__crossx-body > .__crossx-approve-btn,
947
+ .__crossx-card--sign-msg .__crossx-body > .__crossx-approve-btn,
948
+ .__crossx-card--sign-typed .__crossx-body > .__crossx-approve-btn {
949
+ flex-shrink: 0;
950
+ }
951
+
893
952
  /* ── Transaction Progress / Complete Modal ─────────────────── */
894
953
  @keyframes __crossx-spinner {
895
954
  to { transform: rotate(360deg); }
@@ -1149,6 +1208,10 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1149
1208
  overflow: hidden !important;
1150
1209
  }
1151
1210
  .__crossx-card--wallet-selector .__crossx-wallet-list { max-height: 203px; }
1211
+ .__crossx-card--send-tx,
1212
+ .__crossx-card--sign-tx,
1213
+ .__crossx-card--sign-msg,
1214
+ .__crossx-card--sign-typed { overflow: hidden; max-height: 92vh; }
1152
1215
  .__crossx-login-btn-row {
1153
1216
  flex-direction: column;
1154
1217
  }
@@ -1160,7 +1223,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1160
1223
  width: 100% !important;
1161
1224
  max-width: 100% !important;
1162
1225
  border-radius: 20px 20px 0 0 !important;
1163
- border: 1px solid rgba(18,18,18,0.05) !important;
1226
+ border: 1px solid var(--cx-border) !important;
1164
1227
  border-bottom: none !important;
1165
1228
  max-height: 92vh;
1166
1229
  overflow: hidden;
@@ -1196,7 +1259,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1196
1259
  width: 100% !important;
1197
1260
  max-width: 100% !important;
1198
1261
  border-radius: 20px 20px 0 0 !important;
1199
- border: 1px solid rgba(18,18,18,0.05) !important;
1262
+ border: 1px solid var(--cx-border) !important;
1200
1263
  border-bottom: none !important;
1201
1264
  max-height: 92vh;
1202
1265
  overflow: hidden;
@@ -1262,6 +1325,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1262
1325
  flex-direction: column;
1263
1326
  gap: 8px;
1264
1327
  }
1328
+ .__crossx-col-right-sign {
1329
+ display: flex;
1330
+ flex-direction: column;
1331
+ gap: 16px;
1332
+ }
1265
1333
 
1266
1334
  /* ── Landscape for signing/transaction modals ──────────── */
1267
1335
  @media (orientation: landscape) and (max-height: 500px) {
@@ -1276,7 +1344,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1276
1344
  border-radius: 24px;
1277
1345
  border-bottom: 4px solid var(--cx-border);
1278
1346
  max-height: calc(100vh - 32px);
1279
- overflow-y: auto;
1347
+ overflow: hidden;
1280
1348
  animation: __crossx-slide-up 0.18s ease;
1281
1349
  }
1282
1350
  .__crossx-card--send-tx .__crossx-header,
@@ -1301,7 +1369,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1301
1369
  .__crossx-card--wallet-selector .__crossx-body-cols {
1302
1370
  flex-direction: row;
1303
1371
  gap: 24px;
1304
- align-items: flex-start;
1372
+ align-items: stretch;
1373
+ overflow: hidden;
1305
1374
  }
1306
1375
  .__crossx-body-cols > * { flex: 1; min-width: 0; }
1307
1376
  .__crossx-col-left { gap: 8px; }
@@ -1310,10 +1379,16 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1310
1379
  flex-direction: column;
1311
1380
  align-items: flex-end;
1312
1381
  }
1313
- .__crossx-card--sign-tx .__crossx-raw-tx { max-height: 120px; }
1382
+ .__crossx-card--send-tx .__crossx-col-left,
1383
+ .__crossx-card--sign-tx .__crossx-col-left,
1384
+ .__crossx-card--sign-msg .__crossx-col-left,
1385
+ .__crossx-card--sign-typed .__crossx-col-left,
1386
+ .__crossx-card--sign-tx .__crossx-col-right-sign { overflow-y: auto; }
1387
+ .__crossx-card--sign-tx .__crossx-col-right-sign .__crossx-rows { flex-shrink: 0; }
1388
+ .__crossx-card--sign-tx .__crossx-raw-tx { max-height: none; overflow-y: visible; }
1314
1389
  .__crossx-card--sign-msg .__crossx-msg-raw,
1315
- .__crossx-card--sign-msg .__crossx-msg-box { max-height: 130px; }
1316
- .__crossx-card--sign-typed .__crossx-td-rows { max-height: 130px; overflow-y: auto; }
1390
+ .__crossx-card--sign-msg .__crossx-msg-box { max-height: none; overflow-y: auto; }
1391
+ .__crossx-card--sign-typed .__crossx-td-rows { max-height: none; overflow-y: auto; }
1317
1392
  .__crossx-col-left > .__crossx-divider { display: none; }
1318
1393
  .__crossx-card--wallet-selector {
1319
1394
  overflow: hidden !important;
@@ -1463,7 +1538,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1463
1538
  .__crossx-pin6-header-sub {
1464
1539
  font-size: 14px;
1465
1540
  font-weight: 400;
1466
- color: rgba(18,18,18,0.7);
1541
+ color: var(--cx-subtitle);
1467
1542
  line-height: 1.3;
1468
1543
  margin: 2px 0 0;
1469
1544
  }
@@ -1478,7 +1553,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1478
1553
  .__crossx-pin6-subtitle {
1479
1554
  font-size: 16px;
1480
1555
  font-weight: 500;
1481
- color: rgba(18,18,18,0.5);
1556
+ color: var(--cx-label);
1482
1557
  text-align: center;
1483
1558
  margin: 0;
1484
1559
  line-height: 1.5;
@@ -1497,11 +1572,11 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1497
1572
  height: 48px;
1498
1573
  border-radius: 12px;
1499
1574
  border: none;
1500
- background: rgba(18,18,18,0.05);
1575
+ background: var(--cx-input-bg);
1501
1576
  font-size: 24px;
1502
1577
  font-weight: 600;
1503
1578
  text-align: center;
1504
- color: var(--cx-fg, #121212);
1579
+ color: var(--cx-value);
1505
1580
  outline: none;
1506
1581
  caret-color: transparent;
1507
1582
  letter-spacing: 0;
@@ -1509,8 +1584,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1509
1584
  transition: background 0.12s, box-shadow 0.12s;
1510
1585
  }
1511
1586
  .__crossx-pin6-box:focus {
1512
- background: rgba(18,18,18,0.08);
1513
- box-shadow: 0 0 0 2px var(--crossx-primary, #019d92);
1587
+ background: var(--cx-input-border);
1588
+ box-shadow: 0 0 0 2px var(--cx-primary-glow);
1514
1589
  }
1515
1590
  .__crossx-pin6-box.--error {
1516
1591
  /* 에러 시 박스 자체에는 별도 스타일 없음 — 에러 텍스트로만 표시 */
@@ -1533,7 +1608,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1533
1608
  .__crossx-pin6-error {
1534
1609
  font-size: 14px;
1535
1610
  font-weight: 400;
1536
- color: var(--cx-error, #e70077);
1611
+ color: var(--cx-error);
1537
1612
  text-align: center;
1538
1613
  margin: 0;
1539
1614
  min-height: 20px;
@@ -1547,20 +1622,20 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1547
1622
  gap: 6px;
1548
1623
  font-size: 13px;
1549
1624
  font-weight: 500;
1550
- color: var(--crossx-error);
1625
+ color: var(--cx-error);
1551
1626
  text-align: center;
1552
1627
  margin: 0;
1553
1628
  }
1554
1629
  .__crossx-pin6-lock-msg svg {
1555
1630
  flex-shrink: 0;
1556
- color: var(--crossx-error);
1631
+ color: var(--cx-error);
1557
1632
  }
1558
1633
  /* Next 버튼 */
1559
1634
  .__crossx-pin6-next {
1560
1635
  width: 100%;
1561
1636
  padding: 16px;
1562
- background: var(--crossx-primary, #019d92);
1563
- color: white;
1637
+ background: var(--cx-primary);
1638
+ color: var(--cx-on-primary);
1564
1639
  border: none;
1565
1640
  border-radius: 12px;
1566
1641
  font-size: 18px;
@@ -1575,16 +1650,16 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1575
1650
  opacity: 0.5;
1576
1651
  cursor: default;
1577
1652
  }
1578
- `;function ue(){let r=document.getElementById(Kt);r||(r=document.createElement("style"),r.id=Kt,document.head.appendChild(r)),r.textContent=mn}function se(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function wn(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=dt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Yt={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Rs(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Yt[e]?Yt[e]:r}function dt(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 nt(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 yn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function bn(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=yn(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${dt(l,i)} ${o}`,maxFeeGwei:nt(t),maxPriorityFeeGwei:n?nt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${dt(l,i)} ${o}`,gasPriceGwei:nt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Cs(r){const e=bn(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 fe=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1653
+ `;function ue(){let r=document.getElementById(Kt);r||(r=document.createElement("style"),r.id=Kt,document.head.appendChild(r)),r.textContent=mn}function se(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function wn(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=dt(t,s);return n==="0"?null:`${n} ${e}`}catch{return null}}const Yt={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Rs(r){const e=parseInt(r.split(":")[1]??"",10);return!isNaN(e)&&Yt[e]?Yt[e]:r}function dt(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 nt(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 yn(r){try{return BigInt(r).toLocaleString()}catch{return r}}function bn(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=yn(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${dt(l,i)} ${o}`,maxFeeGwei:nt(t),maxPriorityFeeGwei:n?nt(n):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${dt(l,i)} ${o}`,gasPriceGwei:nt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ns(r){const e=bn(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 fe=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
1579
1654
  <rect x="9" y="9" width="13" height="13" rx="2"/>
1580
1655
  <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
1581
1656
  </svg>`,ie=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
1582
1657
  <line x1="18" y1="6" x2="6" y2="18"/>
1583
1658
  <line x1="6" y1="6" x2="18" y2="18"/>
1584
- </svg>`;function vn(r){return`<svg width="28" height="28" viewBox="0 0 28 28" fill="none">
1585
- <circle cx="14" cy="14" r="14" fill="${r}"/>
1586
- <path d="M14 7.5L19.2 10.5V16.5L14 19.5L8.8 16.5V10.5L14 7.5Z" fill="white" opacity="0.9"/>
1587
- </svg>`}const wt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
1659
+ </svg>`,vn=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
1660
+ <circle cx="20" cy="20" r="20" fill="#00D5AA"/>
1661
+ <path fill-rule="evenodd" clip-rule="evenodd" d="M20.3225 2.85742L23.7249 6.25982V11.8301L28.1175 7.43757L32.9292 12.2493L28.5806 16.5979H20.3225C18.4435 16.5979 16.9201 18.1212 16.9201 20.0003C16.9201 21.8794 18.4434 23.4027 20.3225 23.4027H28.5372L32.9293 27.7948L28.1176 32.6066L23.7249 28.2139V33.7407L20.3225 37.1431L16.9201 33.7407V28.2584L12.5719 32.6066L7.76022 27.7948L12.1524 23.4027H6.58209L3.17969 20.0003L6.58209 16.5979H12.1089L7.76035 12.2493L12.5721 7.43757L16.9201 11.7857V6.25982L20.3225 2.85742Z" fill="#121212"/>
1662
+ </svg>`,wt=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none">
1588
1663
  <rect x="2" y="5" width="16" height="12" rx="2" stroke="currentColor" stroke-width="1.5"/>
1589
1664
  <path d="M2 9h16" stroke="currentColor" stroke-width="1.5"/>
1590
1665
  <rect x="12.5" y="11.5" width="3.5" height="2.5" rx="0.75" fill="currentColor"/>
@@ -1598,8 +1673,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1598
1673
  <div class="__crossx-row">
1599
1674
  <span class="__crossx-row-label">${r}</span>
1600
1675
  <div class="__crossx-row-value">${e}</div>
1601
- </div>`}function En(r,e){const s=e,t=Ze(),n=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
1602
- <button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${fe}</button>`:"<span>—</span>",o=Cs(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
1676
+ </div>`}function En(r,e){const s=e,t=Ze(r.dappName),n=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
1677
+ <button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${fe}</button>`:"<span>—</span>",o=Ns(r),i=r.data??"0x",a=document.createElement("div");return a.id=te,a.innerHTML=`
1603
1678
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1604
1679
  <div class="__crossx-header">
1605
1680
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
@@ -1617,14 +1692,16 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1617
1692
  <span class="__crossx-addr-pill-text">${se(r.from)}</span>
1618
1693
  </div>
1619
1694
  <p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
1620
- <hr class="__crossx-divider">
1695
+ </div>
1696
+ <hr class="__crossx-divider __crossx-divider--cols">
1697
+ <div class="__crossx-col-right-sign">
1621
1698
  <div class="__crossx-rows">
1622
1699
  ${Y("To",n)}
1623
1700
  ${Y("Network",`<span>${Rs(r.chainId)}</span>`)}
1624
1701
  ${o}
1625
1702
  </div>
1703
+ <pre class="__crossx-raw-tx">${U(i)}</pre>
1626
1704
  </div>
1627
- <pre class="__crossx-raw-tx">${U(i)}</pre>
1628
1705
  </div>
1629
1706
  <div class="__crossx-btn-row">
1630
1707
  <button class="__crossx-cancel-btn" id="__crossx-cancel-btn">Cancel</button>
@@ -1632,8 +1709,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1632
1709
  </div>
1633
1710
  </div>
1634
1711
  </div>
1635
- `,a}function Tn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=Ze(),i=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
1636
- <button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${fe}</button>`:"<span>—</span>",a=Cs(r),l=wn(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
1712
+ `,a}function Tn(r,e){const s=e,t=r.nativeSymbol??"ETH",n=r.nativeDecimals??18,o=Ze(r.dappName),i=r.to?`<span class="__crossx-addr-text">${se(r.to)}</span>
1713
+ <button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${fe}</button>`:"<span>—</span>",a=Ns(r),l=wn(r.value,t,n)??"—",d=document.createElement("div");return d.id=te,d.innerHTML=`
1637
1714
  <div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1638
1715
  <div class="__crossx-header">
1639
1716
  <p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
@@ -1658,7 +1735,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1658
1735
  <button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
1659
1736
  </div>
1660
1737
  </div>
1661
- `,d}function Ze(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function U(r){return r.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function An(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function kn(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 Pn(r,e){const s=Y("From",`<span class="__crossx-addr-text">${se(r.from)}</span>
1738
+ `,d}function Ze(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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function An(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function kn(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 Pn(r,e){const s=Y("From",`<span class="__crossx-addr-text">${se(r.from)}</span>
1662
1739
  <button class="__crossx-copy-btn" data-copy="${U(r.from)}" title="Copy address">${fe}</button>`),t=r.to?Y("To",`<span class="__crossx-addr-text">${se(r.to)}</span>
1663
1740
  <button class="__crossx-copy-btn" data-copy="${U(r.to)}" title="Copy address">${fe}</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>
1664
1741
  <button class="__crossx-copy-btn" data-copy="${U(r.txHash)}" title="Copy hash">${fe}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
@@ -1696,7 +1773,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1696
1773
  </div>
1697
1774
  </div>
1698
1775
  </div>
1699
- `,s}function Cn(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?In:t?"":Sn,E=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>${E}</span>`):o.textContent=E}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>
1776
+ `,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?In:t?"":Sn,E=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>${E}</span>`):o.textContent=E}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>
1700
1777
  <button class="__crossx-copy-btn" data-copy="${U(e.from)}" title="Copy address">${fe}</button>`):"",l=e.to?Y("To",`<span class="__crossx-addr-text">${se(e.to)}</span>
1701
1778
  <button class="__crossx-copy-btn" data-copy="${U(e.to)}" title="Copy address">${fe}</button>`):"",d=e.amount?Y("Transfer",`<span>${U(e.amount)}</span>`):"",h=e.fees?Y("Tx Fee",`<span>${U(e.fees)}</span>`):"",m=e.txHash?Y("Tx Hash",`<span class="__crossx-addr-text">${se(e.txHash)}</span>
1702
1779
  <button class="__crossx-copy-btn" data-copy="${U(e.txHash)}" title="Copy hash">${fe}</button>`):"",g=e.total?`<div class="__crossx-total-pill">
@@ -1712,7 +1789,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1712
1789
  </div>
1713
1790
  ${g}
1714
1791
  <button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
1715
- `,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",E=>{var S;E.stopPropagation();const y=w.dataset.copy;y&&((S=navigator.clipboard)==null||S.writeText(y).catch(()=>{}))})})}function Nn(r,e){const s=e,t=Ze(),n=U(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
1792
+ `,a.querySelectorAll(".__crossx-copy-btn").forEach(w=>{w.addEventListener("click",E=>{var S;E.stopPropagation();const y=w.dataset.copy;y&&((S=navigator.clipboard)==null||S.writeText(y).catch(()=>{}))})})}function Cn(r,e){const s=e,t=Ze(r.dappName),n=U(r.message),o=document.createElement("div");return o.id=te,o.innerHTML=`
1716
1793
  <div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1717
1794
  <div class="__crossx-header">
1718
1795
  <p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
@@ -1740,7 +1817,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1740
1817
  </div>
1741
1818
  </div>
1742
1819
  </div>
1743
- `,o}function On(r,e){const s=e,t=Ze();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=`
1820
+ `,o}function On(r,e){const s=e,t=Ze(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=`
1744
1821
  <div class="__crossx-td-row">
1745
1822
  <span class="__crossx-td-label">Primary Type</span>
1746
1823
  <span class="__crossx-td-value">${U(o)}</span>
@@ -1862,8 +1939,8 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1862
1939
  <p class="__crossx-mig-info-desc">It safely restores and integrates all your previous assets. Simply verify your PIN to get started.</p>
1863
1940
  </div>
1864
1941
  <button class="__crossx-recover-btn" id="__crossx-recover-btn">
1865
- <span>${vn(e.primary)}</span>
1866
- <span class="__crossx-recover-label">Recover My Wallet</span>
1942
+ <span class="__crossx-recover-icon">${vn}</span>
1943
+ <span class="__crossx-recover-label">Import from Social Backup</span>
1867
1944
  </button>
1868
1945
  <button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
1869
1946
  </div>
@@ -1871,7 +1948,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1871
1948
  `,s}function Hn(r,e){const s=r,{errorMessage:t,attemptCount:n,maxAttempts:o=5}=e??{},i=!!t,a=i?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${o}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",d=i?`<p class="__crossx-pin-error-text">${t}</p>`:"",h=document.createElement("div");return h.id=te,h.innerHTML=`
1872
1949
  <div class="__crossx-card __crossx-card--migration" style="${ce(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1873
1950
  <div class="__crossx-header">
1874
- <p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
1951
+ <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
1875
1952
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
1876
1953
  </div>
1877
1954
  <hr class="__crossx-divider">
@@ -1891,7 +1968,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1891
1968
  `,h}function Fn(r){const e=new Date(r),s=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=s[e.getDay()],o=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${o} ${i} ${a}:${c}`}function Gn(r,e,s){const t=r,n=e<=0,o=n?null:Date.now()+e*1e3,i=o?Fn(o):null,a=document.createElement("div");return a.id=te,a.innerHTML=`
1892
1969
  <div class="__crossx-card __crossx-card--migration" style="${ce(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1893
1970
  <div class="__crossx-header">
1894
- <p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
1971
+ <p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
1895
1972
  <button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ie}</button>
1896
1973
  </div>
1897
1974
  <hr class="__crossx-divider">
@@ -1941,7 +2018,7 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1941
2018
  </div>
1942
2019
  <div class="__crossx-home-indicator"></div>
1943
2020
  `}function ot(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">
1944
- ${Ns}
2021
+ ${Cs}
1945
2022
  <span id="__crossx-pin6-lock-countdown"></span>
1946
2023
  </p>`:"",a=e?" --locked":"",c=Array.from({length:6},(l,d)=>`<input class="__crossx-pin6-box${a}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${d+1}"${e?" disabled":""}>`).join("");return`
1947
2024
  <div class="__crossx-header">
@@ -1963,10 +2040,10 @@ ${t.length}`),o=new Uint8Array(n.length+t.length);o.set(n,0),o.set(t,n.length);c
1963
2040
  <div class="__crossx-card __crossx-card--pin6" style="${ce(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
1964
2041
  ${e}
1965
2042
  </div>
1966
- `,s}function qn(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 Vn(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 it(r,e,s,t,n,o){let i=!!(o&&o>Date.now()),a=!1;const c=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),l=()=>r.querySelector("#__crossx-pin6-boxes"),d=()=>r.querySelector("#__crossx-pin6-error"),h=()=>r.querySelector("#__crossx-pin6-lock-msg"),m=()=>r.querySelector("#__crossx-pin6-lock-countdown"),g=()=>r.querySelector(".__crossx-pin6-body"),w=()=>c().map(v=>v.value).join(""),E=v=>{i=v,c().forEach(P=>{P.disabled=v,P.classList.toggle("--locked",v)})},y=()=>{const v=d();v&&(v.textContent="")},S=v=>{const P=d();P&&(P.textContent=v);const C=l();C==null||C.classList.add("--shake"),setTimeout(()=>C==null?void 0:C.classList.remove("--shake"),500),c().forEach(G=>{G.value=""}),setTimeout(()=>{var G;return(G=c()[0])==null?void 0:G.focus()},50)},O=v=>{var W;E(!0),c().forEach(q=>{q.value=""});const P=d();if(P&&(P.textContent="Too many failed attempts. Please wait."),!h()){const q=document.createElement("p");q.className="__crossx-pin6-lock-msg",q.id="__crossx-pin6-lock-msg",q.innerHTML=`${Ns}<span id="__crossx-pin6-lock-countdown"></span>`;const D=d();D?D.insertAdjacentElement("afterend",q):(W=g())==null||W.appendChild(q)}const C=()=>{var k;const q=v-Date.now(),D=m();q<=0?(clearInterval(G),E(!1),(k=h())==null||k.remove(),P&&(P.textContent=""),setTimeout(()=>{var R;return(R=c()[0])==null?void 0:R.focus()},50)):D&&(D.textContent=` ${Vn(q)}`)},G=setInterval(C,1e3);C();const K=new MutationObserver(()=>{document.contains(r)||(clearInterval(G),K.disconnect())});K.observe(document.body,{childList:!0,subtree:!1})},B=async()=>{if(i||a)return;const v=w();if(v.length===6){a=!0,c().forEach(P=>{P.disabled=!0});try{if(n){const P=await n(v);P.ok?e(v):P.lockExpiresAt?O(P.lockExpiresAt):S(P.error??"Incorrect PIN. Please try again.")}else e(v)}catch(P){t&&t(P)}finally{a=!1,i||c().forEach(P=>{P.disabled=!1})}}};o&&o>Date.now()?O(o):setTimeout(()=>{var v;return(v=c()[0])==null?void 0:v.focus()},100),c().forEach((v,P)=>{v.addEventListener("input",()=>{var G;const C=v.value.replace(/\D/g,"").slice(-1);v.value=C,y(),C&&P<5&&((G=c()[P+1])==null||G.focus()),w().length===6&&setTimeout(B,80)}),v.addEventListener("keydown",C=>{var G,K;if(C.key==="Backspace"){if(C.preventDefault(),v.value)v.value="";else if(P>0){const W=c()[P-1];W.value="",W.focus()}}else C.key==="ArrowLeft"&&P>0?(C.preventDefault(),(G=c()[P-1])==null||G.focus()):C.key==="ArrowRight"&&P<5?(C.preventDefault(),(K=c()[P+1])==null||K.focus()):C.key==="Escape"&&s()}),v.addEventListener("paste",C=>{var W,q;C.preventDefault();const G=(((W=C.clipboardData)==null?void 0:W.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!G)return;const K=c();G.split("").forEach((D,k)=>{K[k]&&(K[k].value=D)}),(q=K[Math.min(G.length-1,5)])==null||q.focus(),y(),w().length===6&&setTimeout(B,80)}),v.addEventListener("focus",()=>v.select())})}const Ns=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
2043
+ `,s}function qn(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 Vn(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 it(r,e,s,t,n,o){let i=!!(o&&o>Date.now()),a=!1;const c=()=>Array.from(r.querySelectorAll(".__crossx-pin6-box")),l=()=>r.querySelector("#__crossx-pin6-boxes"),d=()=>r.querySelector("#__crossx-pin6-error"),h=()=>r.querySelector("#__crossx-pin6-lock-msg"),m=()=>r.querySelector("#__crossx-pin6-lock-countdown"),g=()=>r.querySelector(".__crossx-pin6-body"),w=()=>c().map(v=>v.value).join(""),E=v=>{i=v,c().forEach(P=>{P.disabled=v,P.classList.toggle("--locked",v)})},y=()=>{const v=d();v&&(v.textContent="")},S=v=>{const P=d();P&&(P.textContent=v);const N=l();N==null||N.classList.add("--shake"),setTimeout(()=>N==null?void 0:N.classList.remove("--shake"),500),c().forEach(G=>{G.value=""}),setTimeout(()=>{var G;return(G=c()[0])==null?void 0:G.focus()},50)},O=v=>{var W;E(!0),c().forEach(q=>{q.value=""});const P=d();if(P&&(P.textContent="Too many failed attempts. Please wait."),!h()){const q=document.createElement("p");q.className="__crossx-pin6-lock-msg",q.id="__crossx-pin6-lock-msg",q.innerHTML=`${Cs}<span id="__crossx-pin6-lock-countdown"></span>`;const D=d();D?D.insertAdjacentElement("afterend",q):(W=g())==null||W.appendChild(q)}const N=()=>{var k;const q=v-Date.now(),D=m();q<=0?(clearInterval(G),E(!1),(k=h())==null||k.remove(),P&&(P.textContent=""),setTimeout(()=>{var R;return(R=c()[0])==null?void 0:R.focus()},50)):D&&(D.textContent=` ${Vn(q)}`)},G=setInterval(N,1e3);N();const K=new MutationObserver(()=>{document.contains(r)||(clearInterval(G),K.disconnect())});K.observe(document.body,{childList:!0,subtree:!1})},B=async()=>{if(i||a)return;const v=w();if(v.length===6){a=!0,c().forEach(P=>{P.disabled=!0});try{if(n){const P=await n(v);P.ok?e(v):P.lockExpiresAt?O(P.lockExpiresAt):S(P.error??"Incorrect PIN. Please try again.")}else e(v)}catch(P){t&&t(P)}finally{a=!1,i||c().forEach(P=>{P.disabled=!1})}}};o&&o>Date.now()?O(o):setTimeout(()=>{var v;return(v=c()[0])==null?void 0:v.focus()},100),c().forEach((v,P)=>{v.addEventListener("input",()=>{var G;const N=v.value.replace(/\D/g,"").slice(-1);v.value=N,y(),N&&P<5&&((G=c()[P+1])==null||G.focus()),w().length===6&&setTimeout(B,80)}),v.addEventListener("keydown",N=>{var G,K;if(N.key==="Backspace"){if(N.preventDefault(),v.value)v.value="";else if(P>0){const W=c()[P-1];W.value="",W.focus()}}else N.key==="ArrowLeft"&&P>0?(N.preventDefault(),(G=c()[P-1])==null||G.focus()):N.key==="ArrowRight"&&P<5?(N.preventDefault(),(K=c()[P+1])==null||K.focus()):N.key==="Escape"&&s()}),v.addEventListener("paste",N=>{var W,q;N.preventDefault();const G=(((W=N.clipboardData)==null?void 0:W.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!G)return;const K=c();G.split("").forEach((D,k)=>{K[k]&&(K[k].value=D)}),(q=K[Math.min(G.length-1,5)])==null||q.focus(),y(),w().length===6&&setTimeout(B,80)}),v.addEventListener("focus",()=>v.select())})}const Cs=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
1967
2044
  <path d="M14.5 8.5H14V6.5C14 4.015 11.985 2 9.5 2C7.015 2 5 4.015 5 6.5V8.5H4.5C3.672 8.5 3 9.172 3 10V16.5C3 17.328 3.672 18 4.5 18H14.5C15.328 18 16 17.328 16 16.5V10C16 9.172 15.328 8.5 14.5 8.5ZM10.5 13.415V15C10.5 15.276 10.276 15.5 10 15.5H9C8.724 15.5 8.5 15.276 8.5 15V13.415C8.187 13.196 8 12.847 8 12.5C8 11.672 8.672 11 9.5 11C10.328 11 11 11.672 11 12.5C11 12.847 10.813 13.196 10.5 13.415ZM12.5 8.5H6.5V6.5C6.5 4.843 7.843 3.5 9.5 3.5C11.157 3.5 12.5 4.843 12.5 6.5V8.5Z" fill="currentColor"/>
1968
2045
  </svg>`,zn=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
1969
2046
  <path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
1970
2047
  </svg>`,Kn=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
1971
2048
  <path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="currentColor"/>
1972
- </svg>`;function jn(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((h,m)=>{t[m]&&(t[m].value=h)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class Yn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=jt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=jt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var E;ue();const o=[...e],i=Dn(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const S=y.dataset.walletAddress??"",O=parseInt(y.dataset.walletIndex??"0",10);d({address:S,index:O})})})})();const g=i.querySelector("#__crossx-add-wallet-btn");g&&g.addEventListener("click",async()=>{g.disabled=!0;try{const y=await s();o.push(y);const S=i.querySelector("#__crossx-wallet-list");if(S){const O=document.createElement("button");O.className="__crossx-wallet-item",O.dataset.walletIndex=String(y.index),O.dataset.walletAddress=y.address,O.innerHTML=`<span class="__crossx-wallet-addr">${se(y.address)}</span>`,O.addEventListener("click",()=>d(y)),S.appendChild(O),O.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{g.disabled=!1}}),(E=i.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(){return new Promise(e=>{var a,c,l;ue();const s=Bn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",h=>h.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;ue();const s=Un(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinSetupPrompt(e){return new Promise(s=>{ue();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=Jt(this.tokens,Wn(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=O=>{d(),s(O)},m=()=>{d(),s(null)},g=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},E=O=>{var B;g.innerHTML=ot({title:i.title,headerSubtitle:i.headerSubtitle}),(B=g.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",m),it(g,v=>{v===O?h(O):y(o.mismatchError)},m)},y=O=>{var B;g.innerHTML=ot({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:O}),(B=g.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",m),it(g,v=>{const P=qn(v,w);P?y(P):E(v)},m)};(()=>{var q;const O=Array.from(g.querySelectorAll(".__crossx-pw-notice-item")),B=g.querySelector("#__crossx-pin-notice-next"),v=new Set;B.removeAttribute("disabled");const P=B.dataset.nextLabel??"Next",C=B.dataset.submitLabel??"I Understand",G=()=>{const D=v.size===O.length;B.classList.toggle("--disabled",!D),B.textContent=D?C:P},K=(D,k)=>{if(v.has(k))return;const R=D.querySelector(`#__crossx-notice-check-${k}`);v.add(k),R.classList.add("--checked"),D.setAttribute("aria-checked","true"),G()},W=(D,k)=>{if(!v.has(k))return;const R=D.querySelector(`#__crossx-notice-check-${k}`);v.delete(k),R.classList.remove("--checked"),D.setAttribute("aria-checked","false"),G()};O.forEach(D=>{const k=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{v.has(k)?W(D,k):K(D,k)}),D.addEventListener("keydown",R=>{(R.key===" "||R.key==="Enter")&&(R.preventDefault(),v.has(k)?W(D,k):K(D,k))})}),B.addEventListener("click",()=>{if(v.size===O.length){y(e==null?void 0:e.errorMessage);return}const D=O.find(R=>{const f=parseInt(R.dataset.checkIndex??"0",10);return!v.has(f)});if(!D)return;const k=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),K(D,k)},400)}),(q=g.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",m)})(),a.addEventListener("click",O=>{O.target===a&&m()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;ue();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=Jt(this.tokens,ot({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt})),l=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(c);let d=!1;const h=()=>{d||(d=!0,c.remove(),document.body.style.overflow=l)},m=S=>{h(),s(S)},g=()=>{h(),s(null)},w=S=>{h(),t(S)},E=c.querySelector(".__crossx-card");(y=E.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",g),it(E,m,g,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",S=>{S.target===c&&g()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;ue();const t=Hn(this.tokens,e);document.body.appendChild(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;ue();const{overlay:n,startCountdown:o}=Gn(this.tokens,e,s);document.body.appendChild(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;ue();const t=Pn(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var m;d.stopPropagation();const h=l.dataset.copy;h&&((m=navigator.clipboard)==null||m.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{ue();const n=Rn(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,h;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",m=>{m.target===n&&a()});const l=m=>{m.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Cn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;ue();let t;e.type==="sign-message"?t=Nn(e,this.tokens):e.type==="sign-typed-data"?t=On(e,this.tokens):e.type==="sign"?t=En(e,this.tokens):t=Tn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",m=>{var w;m.stopPropagation();const g=h.dataset.copy;g&&((w=navigator.clipboard)==null||w.writeText(g).catch(()=>{}))})}),t.addEventListener("click",h=>{h.target===t&&i()});const a=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class Jn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function Zn(r){r.debug;const e=We.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},o=s.authMode!=="cookie"&&Rt.isAvailable()?new Rt:new rr,i=new hn,a=new xn,c=new we,l=new Jn,d=new Qt;let h;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),h=new _n(o,d)):(u.log("[CROSSx] Remote Wallet Provider 사용"),h=new Le(t,o,a,l,d));const m=new De(t,a),g=new Yn(r.theme??"light",r.themeTokens);return new qe(s,t,o,i,a,c,h,l,g,m,d)}exports.CROSSxError=_;exports.CROSSxEthereumProvider=Zt;exports.CROSSxSDK=qe;exports.ChainId=Ms;exports.ErrorCode=p;exports.createCROSSxSDK=Zn;
2049
+ </svg>`;function jn(r,e,s){var n;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((o,i)=>{o.addEventListener("input",()=>{const a=o.value.replace(/\D/g,"");o.value=a?a[0]:"",a&&i<3&&t[i+1].focus();const c=Array.from(t).map(l=>l.value).join("");c.length===4&&setTimeout(()=>e(c),200)}),o.addEventListener("keydown",a=>{a.key==="Backspace"&&!o.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),o.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),o.addEventListener("paste",a=>{var d;a.preventDefault();const c=(((d=a.clipboardData)==null?void 0:d.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!c)return;c.split("").forEach((h,m)=>{t[m]&&(t[m].value=h)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(n=t[0])==null||n.focus()}class Yn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=jt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=jt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(n=>{var E;ue();const o=[...e],i=Dn(o,this.tokens,t),a=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(i);let c=!1;const l=()=>{c||(c=!0,i.remove(),document.body.style.overflow=a)},d=y=>{l(),n(y)},h=()=>{l(),n(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const S=y.dataset.walletAddress??"",O=parseInt(y.dataset.walletIndex??"0",10);d({address:S,index:O})})})})();const g=i.querySelector("#__crossx-add-wallet-btn");g&&g.addEventListener("click",async()=>{g.disabled=!0;try{const y=await s();o.push(y);const S=i.querySelector("#__crossx-wallet-list");if(S){const O=document.createElement("button");O.className="__crossx-wallet-item",O.dataset.walletIndex=String(y.index),O.dataset.walletAddress=y.address,O.innerHTML=`<span class="__crossx-wallet-addr">${se(y.address)}</span>`,O.addEventListener("click",()=>d(y)),S.appendChild(O),O.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{g.disabled=!1}}),(E=i.querySelector("#__crossx-close-btn"))==null||E.addEventListener("click",h),i.addEventListener("click",y=>{y.target===i&&h()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),h())};document.addEventListener("keydown",w)})}showLoginSelector(){return new Promise(e=>{var a,c,l;ue();const s=Bn(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=d=>{t(),e(d)},o=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>n("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>n("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",h=>h.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;ue();const s=Un(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),n=()=>{t(),e("recover")},o=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",n),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",o),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",o),s.addEventListener("click",d=>{d.target===s&&o()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showPinSetupPrompt(e){return new Promise(s=>{ue();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=Jt(this.tokens,Wn(n)),c=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),document.body.style.overflow=c)},h=O=>{d(),s(O)},m=()=>{d(),s(null)},g=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},E=O=>{var B;g.innerHTML=ot({title:i.title,headerSubtitle:i.headerSubtitle}),(B=g.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",m),it(g,v=>{v===O?h(O):y(o.mismatchError)},m)},y=O=>{var B;g.innerHTML=ot({title:o.title,headerSubtitle:o.headerSubtitle,subtitle:o.subtitle,errorMessage:O}),(B=g.querySelector("#__crossx-close-btn"))==null||B.addEventListener("click",m),it(g,v=>{const P=qn(v,w);P?y(P):E(v)},m)};(()=>{var q;const O=Array.from(g.querySelectorAll(".__crossx-pw-notice-item")),B=g.querySelector("#__crossx-pin-notice-next"),v=new Set;B.removeAttribute("disabled");const P=B.dataset.nextLabel??"Next",N=B.dataset.submitLabel??"I Understand",G=()=>{const D=v.size===O.length;B.classList.toggle("--disabled",!D),B.textContent=D?N:P},K=(D,k)=>{if(v.has(k))return;const R=D.querySelector(`#__crossx-notice-check-${k}`);v.add(k),R.classList.add("--checked"),D.setAttribute("aria-checked","true"),G()},W=(D,k)=>{if(!v.has(k))return;const R=D.querySelector(`#__crossx-notice-check-${k}`);v.delete(k),R.classList.remove("--checked"),D.setAttribute("aria-checked","false"),G()};O.forEach(D=>{const k=parseInt(D.dataset.checkIndex??"0",10);D.addEventListener("click",()=>{v.has(k)?W(D,k):K(D,k)}),D.addEventListener("keydown",R=>{(R.key===" "||R.key==="Enter")&&(R.preventDefault(),v.has(k)?W(D,k):K(D,k))})}),B.addEventListener("click",()=>{if(v.size===O.length){y(e==null?void 0:e.errorMessage);return}const D=O.find(R=>{const f=parseInt(R.dataset.checkIndex??"0",10);return!v.has(f)});if(!D)return;const k=parseInt(D.dataset.checkIndex??"0",10);D.scrollIntoView({behavior:"smooth",block:"nearest"}),D.classList.add("--highlight"),setTimeout(()=>{D.classList.remove("--highlight"),K(D,k)},400)}),(q=g.querySelector("#__crossx-close-btn"))==null||q.addEventListener("click",m)})(),a.addEventListener("click",O=>{O.target===a&&m()})})}showPinInputPrompt(e){return new Promise((s,t)=>{var y;ue();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=Jt(this.tokens,ot({title:i,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt})),l=document.body.style.overflow;document.body.style.overflow="hidden",document.body.appendChild(c);let d=!1;const h=()=>{d||(d=!0,c.remove(),document.body.style.overflow=l)},m=S=>{h(),s(S)},g=()=>{h(),s(null)},w=S=>{h(),t(S)},E=c.querySelector(".__crossx-card");(y=E.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",g),it(E,m,g,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",S=>{S.target===c&&g()})})}showRecoveryPinInputPrompt(e){return new Promise(s=>{var a;ue();const t=Hn(this.tokens,e);document.body.appendChild(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;ue();const{overlay:n,startCountdown:o}=Gn(this.tokens,e,s);document.body.appendChild(n);const i=()=>{c(),n.remove()},a=()=>{i(),t()},c=o(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;ue();const t=Pn(e,this.tokens);document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",o),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var m;d.stopPropagation();const h=l.dataset.copy;h&&((m=navigator.clipboard)==null||m.writeText(h).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&o()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),o())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{ue();const n=Rn(e,this.tokens);document.body.appendChild(n);const o=()=>n.remove();let i=!1;const a=()=>{i||(i=!0,o(),t())},c=()=>{var d,h;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(h=n.querySelector("#__crossx-close-btn"))==null||h.addEventListener("click",a),n.addEventListener("click",m=>{m.target===n&&a()});const l=m=>{m.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Nn(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;ue();let t;e.type==="sign-message"?t=Cn(e,this.tokens):e.type==="sign-typed-data"?t=On(e,this.tokens):e.type==="sign"?t=En(e,this.tokens):t=Tn(e,this.tokens),document.body.appendChild(t);const n=()=>t.remove(),o=()=>{n(),s(!0)},i=()=>{n(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",o),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",i),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(h=>{h.addEventListener("click",m=>{var w;m.stopPropagation();const g=h.dataset.copy;g&&((w=navigator.clipboard)==null||w.writeText(g).catch(()=>{}))})}),t.addEventListener("click",h=>{h.target===t&&i()});const a=h=>{h.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class Jn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function Zn(r){r.debug;const e=We.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},o=s.authMode!=="cookie"&&Rt.isAvailable()?new Rt:new rr,i=new hn,a=new _n,c=new we,l=new Jn,d=new Qt;let h;r.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),h=new xn(o,d)):(u.log("[CROSSx] Remote Wallet Provider 사용"),h=new Le(t,o,a,l,d));const m=new De(t,a),g=new Yn(r.theme??"light",r.themeTokens);return new qe(s,t,o,i,a,c,h,l,g,m,d)}exports.CROSSxError=x;exports.CROSSxEthereumProvider=Zt;exports.CROSSxSDK=qe;exports.ChainId=Ms;exports.ErrorCode=p;exports.createCROSSxSDK=Zn;