@nexus-cross/crossx-sdk-core 1.1.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/__tests__/mocks/MockWalletProviderPort.d.ts.map +1 -1
- package/dist/adapters/confirmation/BrowserConfirmationAdapter.d.ts.map +1 -1
- package/dist/adapters/crypto/JoseCryptoAdapter.d.ts +1 -1
- package/dist/adapters/crypto/JoseCryptoAdapter.d.ts.map +1 -1
- package/dist/adapters/transport/FetchTransportAdapter.d.ts.map +1 -1
- package/dist/adapters/wallet/RemoteWalletProviderAdapter.d.ts.map +1 -1
- package/dist/adapters/wallet/types.d.ts +7 -7
- package/dist/adapters/wallet/types.d.ts.map +1 -1
- package/dist/core/ports/TransportPort.d.ts.map +1 -1
- package/dist/core/ports/WalletProviderPort.d.ts +1 -1
- package/dist/core/services/TypedEventEmitter.d.ts.map +1 -1
- package/dist/core/types/caip.d.ts.map +1 -1
- package/dist/core/types/chain.d.ts +1 -1
- package/dist/core/types/chain.d.ts.map +1 -1
- package/dist/core/types/errors.d.ts +5 -3
- package/dist/core/types/errors.d.ts.map +1 -1
- package/dist/core/types/index.d.ts.map +1 -1
- package/dist/core/utils/logger.d.ts.map +1 -1
- package/dist/crossx.global +51 -51
- package/dist/index.cjs +40 -40
- package/dist/index.js +350 -342
- package/dist/sdk/CROSSxSDK.d.ts +8 -1
- package/dist/sdk/CROSSxSDK.d.ts.map +1 -1
- package/dist/sdk/EthereumProvider.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
"use strict";var Os=Object.defineProperty;var Ns=(r,e,s)=>e in r?Os(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var S=(r,e,s)=>Ns(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ls=require("jose");var g=(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.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.PASSWORD_NOT_SET="PASSWORD_NOT_SET",r.PASSWORD_WRONG="PASSWORD_WRONG",r.PASSWORD_COMPLEXITY="PASSWORD_COMPLEXITY",r.PASSWORD_CANCELLED="PASSWORD_CANCELLED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(g||{});class m extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const ze={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Ds=Object.fromEntries(Object.entries(ze).map(([r,e])=>[r,e.caipId])),Ms=new Map(Object.values(ze).map(r=>[r.caipId,r]));new Map(Object.values(ze).map(r=>[r.chainId,r]));const $s={symbol:"",decimals:18};function Je(r){var e;return((e=Ms.get(r))==null?void 0:e.nativeCurrency)??$s}class Xt{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new m(g.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(g.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(o=>o(...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 ye=null;function St(r){ye=r}const h={log(...r){if(ye){ye.log(...r);return}},warn(...r){if(ye){ye.warn(...r);return}},error(...r){if(ye){ye.error(...r);return}}},Bs={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:"건너뛰기",pinInput_title:"PIN 입력",pinInput_placeholder:"4자리 PIN을 입력하세요",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",passwordNotice_headerSubtitle:"트랜잭션, PK/니모닉 및 계정 삭제 시 필요합니다.",passwordNotice_title:"비밀번호 설정 주의사항",passwordNotice_description:"보안을 위해 이 비밀번호는 재설정하거나 복구할 수 없습니다. 반드시 백업하거나 암기해 두시기 바랍니다.",passwordNotice_check1:"이 비밀번호는 분실 시 복구할 수 없으며, 안전하게 백업해 두었습니다.",passwordNotice_check2:"비밀번호 분실 시 계정 및 모든 관련 데이터에 영구적으로 접근이 불가능해질 수 있습니다.",passwordNotice_check3:"지원팀을 포함한 제3자는 이 비밀번호를 복구하거나 재설정해 줄 수 없습니다.",passwordNotice_nextButton:"다음",passwordNotice_submitButton:"동의합니다",passwordSetup_title:"비밀번호 만들기",passwordSetup_subtitle:"비밀번호는 자산 전송 시에만 사용됩니다.",passwordSetup_newPasswordLabel:"새 비밀번호",passwordSetup_confirmPasswordLabel:"새 비밀번호 확인",passwordSetup_rule_minLength:"8자 이상",passwordSetup_rule_uppercase:"대문자 1자 이상 포함",passwordSetup_rule_number:"숫자 1자 이상 포함",passwordSetup_rule_special:"특수문자 1자 이상 포함",passwordSetup_confirmError:"비밀번호가 일치하지 않습니다",passwordSetup_submitButton:"다음",passwordInput_title:"비밀번호 입력",passwordInput_subtitle:"계속하려면 비밀번호를 입력하세요.",passwordInput_passwordLabel:"비밀번호",passwordInput_submitButton:"확인",passwordInput_error:"비밀번호가 올바르지 않습니다. 다시 시도해 주세요.",verifyPassword_title:"비밀번호 확인",verifyPassword_subtitle:"계속하려면 현재 비밀번호를 확인해 주세요.",verifyPassword_passwordLabel:"비밀번호 확인"},Jt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",pinInput_title:"Enter PIN",pinInput_placeholder:"Enter your 4-digit PIN",pinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",passwordNotice_headerSubtitle:"Required for Transactions, PK/Mnemonic & Account Deletion.",passwordNotice_title:"Password Setup Notice",passwordNotice_description:"For your security, this password cannot be reset or recovered. Please ensure you have it backed up or memorized.",passwordNotice_check1:"This password cannot be recovered if lost, and I have securely backed it up.",passwordNotice_check2:"Losing this password may result in permanent loss of access to my account and all associated data.",passwordNotice_check3:"No third party, including the support team, can recover or reset this password on my behalf.",passwordNotice_nextButton:"Next",passwordNotice_submitButton:"I Understand",passwordSetup_title:"Create Password",passwordSetup_subtitle:"Password is only used to transfer your asset.",passwordSetup_newPasswordLabel:"New Password",passwordSetup_confirmPasswordLabel:"Confirm New Password",passwordSetup_rule_minLength:"Over 8 letters",passwordSetup_rule_uppercase:"Include at least 1 uppercase letter",passwordSetup_rule_number:"Include at least 1 number",passwordSetup_rule_special:"Include at least 1 special character",passwordSetup_confirmError:"Password is incorrect",passwordSetup_submitButton:"Next",passwordInput_title:"Enter Password",passwordInput_subtitle:"Enter your password to continue.",passwordInput_passwordLabel:"Password",passwordInput_submitButton:"Confirm",passwordInput_error:"Incorrect password. Please try again.",verifyPassword_title:"Verify Your Password",verifyPassword_subtitle:"To continue, please confirm your current password",verifyPassword_passwordLabel:"Confirm Password"},Us={ko:Bs,en:Jt};function Et(r="en",e){return Us[r]??Jt}const Qe="crossx_access_token",Ne="crossx_refresh_token",Le="crossx_user_info";class Hs{constructor(e,s,t,o,n,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=o,this.transport=n,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 m(g.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 o=t;if(o.code&&o.code!==200&&o.code>0)throw new m(g.AUTH_FAILED,`${s} 실패 (코드 ${o.code}): ${o.message}`)}}async execute(e){var o,n,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:u}=this.config,_=`${d}${l}`;h.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인):`,_);const f=await this.oauth.openAuth({authUrl:_,expectedOrigin:new URL(d).origin});h.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",f.length,")");const{accessToken:p,refreshToken:b}=await this.exchangeFirebaseToken(f,u);let y,E;try{const U=this.crypto.decodeJWT(f);E=(o=U.firebase)==null?void 0:o.sign_in_provider;const M=((n=U.firebase)==null?void 0:n.identities)??{};E==="google.com"?y=(i=M["google.com"])==null?void 0:i[0]:E==="apple.com"&&(y=(a=M["apple.com"])==null?void 0:a[0]),h.log("[CROSSx] OAuth provider sub 추출 — provider:",E,"hasProviderSub:",!!y)}catch{h.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const U=this.crypto.decodeJWT(p);h.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const M=await this.crypto.verifyJWT(p);if(t=M.signatureVerified??!1,!M.valid)throw h.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const B=M.payload;s={id:B.sub,email:B.email,signInProvider:E,providerSub:y},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(Qe,p),b&&await this.storage.set(Ne,b))}else{const U=this.crypto.decodeJWT(f);s={id:U.sub,email:U.email,signInProvider:E,providerSub:y},h.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}h.log("[CROSSx] 사용자 정보 — id:",s.id);const D=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Le,D),h.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return h.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return h.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,o=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;h.log("[CROSSx] Firebase 토큰 교환 요청:",o);const n=await this.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});h.log("[CROSSx] 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return h.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new m(g.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");h.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 n=t.data,i=n.access_token??n.token;if(typeof i=="string")return i}const o=t.access_token??t.token;if(typeof o=="string")return o}}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 n=t.data,i=n.refresh_token??n.refresh;if(typeof i=="string")return i}const o=t.refresh_token??t.refresh;if(typeof o=="string")return o}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 o=await this.storage.get(Le);if(o)return h.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(o,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){h.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Qe),o=await this.storage.get(Ne);if(h.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",o?"있음":"없음"),!o)return h.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const n=await this.silentRefresh(o);h.log("[CROSSx] restoreSession — silentRefresh 결과:",n?"토큰 발급 성공":"토큰 없음"),n&&this.tokenStore.set(n)}const s=await this.storage.get(Le);if(h.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;h.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return h.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return h.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ne),await this.storage.remove(Le),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,o=`${s}/cross-auth/social/refresh/simple`,n={};if(!t){const l=this.tokenStore.get()??"";l&&(n.access_token=l),e&&(n.refresh_token=e)}const i=await this.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:n,...t?{credentials:"include"}:{}});h.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){h.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new m(g.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(Qe,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ne,l)}return h.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,o=!1;try{if(typeof this.walletProvider.checkWallet=="function"){h.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const n=await this.walletProvider.checkWallet();if(h.log("[CROSSx] 지갑 상태:",n),n==="migration_required")h.log("[CROSSx] migration_required → needsMigration = true"),o=!0;else if(n==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,h.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):h.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){h.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else h.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,h.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(n){if(n instanceof m&&n.code===g.MIGRATION_BACKUP_EXISTS)h.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),o=!0;else{if(n instanceof m&&(n.code===g.PROJECT_NOT_REGISTERED||n.code===g.PROJECT_ID_MISSING||n.code===g.ORIGIN_NOT_ALLOWED))throw h.error("[CROSSx] 프로젝트 설정 에러:",n.message),n;h.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",n)}}return h.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",o),{success:!0,address:t,user:e,needsMigration:o,tokenSignatureVerified:s}}}const Fs="crossx_access_token",Gs="crossx_refresh_token",qs="crossx_user_info";class Ws{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(Fs),await this.storage.remove(Gs)),await this.storage.remove(qs)}}class Vs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new m(g.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");h.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return h.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 o=new Uint8Array(s.length);for(let n=0;n<s.length;n++)o[n]=s[n]^t[n];s.fill(0),this.xorKey=t,this.encryptedBytes=o}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 o=await this.chainRegistry.getChain(t),n={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:o.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:n})).data;if(a!=null&&a.error)throw new m(g.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(o=>o(s))}removeAllListeners(){this.listeners.clear()}}const Fe={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 zs(r){const e=r.environment;return e&&e in Fe?Fe[e]:null}function Ys(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=zs(r);if(e)return e}}catch{}return Fe.production}const Zs=2e3,It=6e4,Xs=1e3,Js=1e4,Qs="0x77359400",At="0x3B9ACA00",Tt=130,Ct=6,kt=18,er=0,tr=30*1e3,Q=class Q extends js{constructor(e,s,t,o,n,i,a,c,l,d,u){super(),this.storage=t,this.crypto=o,this.transport=n,this.oauth=i,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this.authenticated=!1,this.userId=null,this.address=null,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPasswordMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&St(e.logger),this.confirmation=l,this.passwordStore=u??new Qt,this.chainRegistry=d,this.jsonRpc=new Ks(d,n),this.signInUseCase=new Hs(this.internalConfig,t,o,i,n,a,c),this.signOutUseCase=new Ws(this.internalConfig,t,c),this.migrateWalletUseCase=new Vs(t,a)}get config(){return this._config}async initialize(){if(this.initialized)return this.authenticated?{success:!0,address:this.address??void 0}:null;console.log("[CROSSx SDK] v1.1.0 초기화 중..."),this.confirmation.setMessages(Et(this._config.locale));try{const e=Ys();this.internalConfig.oauthServiceUrl=e.oauthServiceUrl,this.internalConfig.authApiUrl=e.authApiUrl,this.internalConfig.walletGatewayUrl=e.walletGatewayUrl,this.adapterConfig.gatewayUrl=e.walletGatewayUrl;const s=await this.signInUseCase.restoreSession();if(s!=null&&s.success){this.applyAuthResult(s);try{await this.loadWalletAfterAuth()}catch(t){if(!(t instanceof m&&t.code===g.PASSWORD_CANCELLED))throw t;h.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(s!=null&&s.success)}),s??null}catch(e){throw new m(g.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",e)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new m(g.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 m(g.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:n}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??n,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),o=await this.selectWalletIfMultiple(t);return{...s,address:(o==null?void 0:o.address)??s.address,addresses:t}}catch(t){throw t instanceof m&&t.code===g.PASSWORD_CANCELLED&&(h.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>h.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(g.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 m&&s.code===g.PASSWORD_CANCELLED||h.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const s=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),h.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof m?s:new m(g.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(g.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:0}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.walletProvider.getAddresses(this.userId);return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(g.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.ensurePasswordForSigning();const o=s.length,i={address:(await this.walletProvider.getAddress(this.userId,o)).address,index:o};return s.push(i),i},e);return t&&(this.address=t.address,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof m?e:new m(g.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof m?s:new m(g.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(Et(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");h.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(h.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;h.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new m(g.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}e==="exists"?await this.ensureVerifiedPassword():await this.ensurePasswordSetup();try{const s=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=s.address,this.emit("addressChanged",{address:s.address,index:0}),h.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===g.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;h.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const o=await this.handleMigrationFlow(t);if(o)return this.address=o.address,this.emit("addressChanged",{address:o.address,index:0}),{address:o.address};throw new m(g.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return h.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=t==null?void 0:t.index,n=await this.walletProvider.getAddress(this.userId,o??0);let i;if(this.walletProvider.prepare&&(i=(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 m(g.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const c=await this.withPasswordRetry(()=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,n.address));return this.verifySignatureSigner(s,c.signature,n.address),{chainId:e,signature:c.signature,message:s,address:n.address}}catch(c){throw c instanceof m?c:new m(g.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new m(g.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");await this.ensurePasswordForSigning(),Q.validateTypedDataChainId(e,s);const o=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let n;if(this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:o.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(g.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const a=await this.withPasswordRetry(()=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,n,o.address));return Q.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:o.address}}catch(a){throw a instanceof m?a:new m(g.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(Q.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=await this.withResolvedGasAndFee(s,e);let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign",{tx:o})).uuid);const i=Je(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:o.from,to:o.to,value:o.value,data:o.data,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(g.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const c=await this.withPasswordRetry(()=>this.walletProvider.signTransaction(this.userId,e,o,t==null?void 0:t.index,n));return Q.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof m)throw c;const l=c instanceof Error?c.message:String(c);throw new m(g.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(g.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=await this.withResolvedGasAndFee(s,e);let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("send",{tx:o})).uuid);const i=Je(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:o.from,to:o.to,value:o.value,data:o.data,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(g.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const c=await this.withPasswordRetry(async()=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,o,n)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,o,t==null?void 0:t.index,n);return l.txHash??l.signature});return{chainId:e,txHash:c,status:"pending"}}catch(c){if(c instanceof m)throw c;const l=c instanceof Error?c.message:String(c);throw new m(g.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 o=t.intervalMs??Xs,n=Js,i=t.timeoutMs??It,a=Date.now()+i;let c=o;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,n)}throw new m(g.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,y;const{intervalMs:o,timeoutMs:n,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=o??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Zs,l=n??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??It,d=Je(e),u=s.from??"";let _,f;const p=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{_=E;const D=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),U=s.value?BigInt(s.value):0n,M=Q.formatTxAmount(s.value,d.symbol,d.decimals),B=Q.formatTxAmount("0x"+D.toString(16),d.symbol,d.decimals),K=Q.formatTxAmount("0x"+(U+D).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:E.from,to:E.to??s.to,amount:M,fees:B,total:K,nativeSymbol:d.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(f=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:u,to:s.to,amount:Q.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:u,to:s.to},p),f)throw f;return{chainId:e,txHash:a,receipt:_}}setPassword(e){this.passwordStore.set(e)}clearPassword(){this.passwordStore.clear()}hasPassword(){return this.passwordStore.has()}async changePassword(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePassword!="function")throw new m(g.NOT_IMPLEMENTED,"changePassword가 구현되어 있지 않습니다");this.passwordStore.set(e);try{await t.changePassword(e,s),this.passwordStore.set(s),h.log("[CROSSx] 비밀번호 변경 완료")}catch(o){throw o instanceof m?o:new m(g.UNKNOWN_ERROR,"비밀번호 변경에 실패했습니다",o)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(g.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(o){const n=o instanceof Error?o.message:String(o);throw new m(g.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${n}`,o)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(g.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(g.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof m)throw t;const o=t instanceof Error?t.message:String(t);throw new m(g.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${o}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const o=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:o,formatted:Q.formatWei(o),chainId:e}}catch(t){if(t instanceof m)throw t;const o=t instanceof Error?t.message:String(t);throw new m(g.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${o}`,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),o=s/t,i=(s%t).toString().padStart(kt,"0").replace(/0+$/,"").slice(0,Ct);return i?`${o}.${i}`:`${o}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Xt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(o){if(o instanceof m)throw o;const n=o instanceof Error?o.message:String(o);throw new m(g.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${n}`,o)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const o=BigInt(e);if(o===0n)return;const n=10n**BigInt(t),i=o/n,c=(o%n).toString().padStart(t,"0").slice(0,Ct).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;h.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(h.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return h.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,o=0,n=5,i=null;for(;;){o++,h.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${n})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showPinInputPrompt({errorMessage:t,attemptCount:o>1?o-1:void 0,maxAttempts:n});if(l===null)return h.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;h.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${l.length}자리) — verify-pin API 호출`),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyPin)==null?void 0:c.call(a,l,e));if(!d){h.log("[CROSSx][Migration Phase 4] verifyPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){h.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const u=d.pinStatus;if(n=u.maxAttempts,o=n-u.remainingAttempts,u.remainingAttempts===0&&u.lockExpiresAt){const _=u.lockExpiresAt*1e3,f=Math.max(1,Math.round((_-Date.now())/1e3)),p=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";h.warn(`[CROSSx][Migration Phase 4] verify-pin 잠금 — ${f}초, 메시지: ${p}`),await this.confirmation.showPinLockedPrompt(f,p),o=0,t="Your account lock has been lifted. You may try again."}else h.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${n})`),t="Incorrect PIN."}catch(d){if(!(d instanceof m))throw d;if(d.code===g.MIGRATION_PIN_LOCKED){const u=d.details;if(n=(u==null?void 0:u.maxAttempts)??5,(u==null?void 0:u.permanent)===!0)return h.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-pin)"),await this.confirmation.showPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const _=((u==null?void 0:u.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((_-Date.now())/1e3)),p=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";h.warn(`[CROSSx][Migration Phase 4] verify-pin 이미 잠금 — ${f}초`),await this.confirmation.showPinLockedPrompt(f,p),o=0,t="Your account lock has been lifted. You may try again."}else throw h.error("[CROSSx][Migration Phase 4] verify-pin 실패 (복구 불가):",d),d}}h.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePasswordSetup();const l=await this.migrateWalletUseCase.execute(i,e);return h.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof m&&l.code===g.MIGRATION_FAILED)return h.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw h.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),o=e.nonce===void 0||e.nonce===null,n=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!o&&!n&&!i&&!a)return e;const c={...e};if(o){const l=c.from??this.address;if(l){h.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),h.log("[CROSSx] nonce 결과:",c.nonce)}}if(n&&(h.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),h.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){h.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=At;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,h.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Qs,h.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=At,h.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=Q.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new m(g.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const o=e.match(/^eip155:(\d+)$/);if(o){const n=Number(o[1]);if(t===void 0)throw new m(g.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==n)throw new m(g.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${n})와 일치하지 않습니다`)}}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 o=Number(t);return Number.isFinite(o)?o:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new m(g.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Tt)throw new m(g.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 m(g.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new m(g.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const o=this.crypto.recoverPersonalSignSigner(e,s);if(o.toLowerCase()!==t.toLowerCase())throw h.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:o}),new m(g.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${o}`);h.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(o){if(o instanceof m)throw o;h.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",o)}}applyAuthResult(e){var s,t,o,n;this.authenticated=e.success,this.userId=((s=e.user)==null?void 0:s.id)??null,this.address=e.address??null,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((o=e.user)==null?void 0:o.providerSub)??null,this.loginType=Q.normalizeLoginType((n=e.user)==null?void 0:n.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.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.passwordStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePasswordSetup(){if(this.passwordStore.has())return;const e=await this.confirmation.showPasswordSetupPrompt();if(!e)throw new m(g.PASSWORD_CANCELLED,"사용자가 비밀번호 설정을 취소했습니다");this.passwordStore.set(e),h.log("[CROSSx] 비밀번호 설정 완료 (메모리 캐시)")}async ensurePasswordForSigning(e){if(this.passwordStore.has()&&!e)return;e&&this.passwordStore.clear();const s=await this.confirmation.showPasswordInputPrompt({errorMessage:e});if(!s)throw new m(g.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");this.passwordStore.set(s),h.log("[CROSSx] 비밀번호 입력 완료 (메모리 캐시)")}async ensureVerifiedPassword(e){if(e)this.passwordStore.clear();else if(this.passwordStore.has())return;if(this._verifyPasswordMutex&&!e){h.log("[CROSSx] ensureVerifiedPassword: 진행 중인 검증 대기"),await this._verifyPasswordMutex;return}let s,t;this._verifyPasswordMutex=new Promise((o,n)=>{s=o,t=n});try{if(typeof this.walletProvider.verifyPassword!="function"){const n=await this.confirmation.showPasswordInputPrompt({verifyMode:!0,errorMessage:e});if(!n)throw new m(g.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");this.passwordStore.set(n),h.log("[CROSSx] 비밀번호 캐시 완료 (verifyPassword 미지원, 로컬 전용)"),s();return}if(!await this.confirmation.showPasswordInputPrompt({verifyMode:!0,errorMessage:e,onSubmit:async n=>{this.passwordStore.set(n);try{return await this.walletProvider.verifyPassword(n)?(h.log("[CROSSx] 비밀번호 서버 검증 완료 (verify-password)"),{ok:!0}):(this.passwordStore.clear(),{ok:!1,error:"Incorrect password. Please try again."})}catch(i){if(this.passwordStore.clear(),i instanceof m&&i.code===g.PASSWORD_WRONG)return{ok:!1,error:"Incorrect password. Please try again."};throw i}}}))throw new m(g.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");s()}catch(o){throw t(o),o}finally{this._verifyPasswordMutex=null}}async loadWalletAfterAuth(){if(!this.userId)return;const e=await this.fetchWalletStatus();if(h.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",e),e!=="exists")return;const s=await this.walletProvider.getAddresses(this.userId);if(s.length>0){this.address=s[0].address,this.emit("addressChanged",{address:s[0].address,index:s[0].index}),h.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address);return}h.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPassword();const t=await this.walletProvider.getAddress(this.userId,0);this.address=t.address,this.emit("addressChanged",{address:t.address,index:0}),h.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address)}async withPasswordRetry(e){try{return await e()}catch(s){if(s instanceof m&&s.code===g.PASSWORD_WRONG)return h.warn("[CROSSx] 비밀번호 불일치 — 서버 검증 후 재시도"),await this.ensureVerifiedPassword("Incorrect password. Please enter your current password."),await e();throw s}}ensureInitialized(){if(!this.initialized)throw new m(g.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(g.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.passwordStore.clear(),this.initialized=!1,this.removeAllListeners(),St(null)}};Q.OFFCHAIN_CHAIN_ID="0";let Ge=Q;class sr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw h.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 h.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw h.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw h.error("Storage clear error:",e),e}}}const rr="crossx-sdk",or=1,Se="data",De="keys",Rt="aes-primary",nr=12;class Pt{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(rr,or);t.onupgradeneeded=()=>{const o=t.result;o.objectStoreNames.contains(Se)||o.createObjectStore(Se),o.objectStoreNames.contains(De)||o.createObjectStore(De)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,o)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>o(i.error)})}idbPut(e,s,t){return new Promise((o,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>o(),a.onerror=()=>n(a.error)})}idbDelete(e,s){return new Promise((t,o)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>o(i.error)})}idbClear(e){return new Promise((s,t)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).clear();n.onsuccess=()=>s(),n.onerror=()=>t(n.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(De,Rt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(De,Rt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(nr);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:o}}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),o=await this.encrypt(t);await this.idbPut(Se,e,o)}catch(t){throw h.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Se,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return h.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw h.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw h.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 dt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function pe(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function F(r,e,s=""){const t=dt(r),o=r==null?void 0:r.length,n=e!==void 0;if(!t||n&&o!==e){const i=s&&`"${s}" `,a=n?` of length ${e}`:"",c=t?`length=${o}`:`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");pe(r.outputLen),pe(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){F(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function ir(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Te(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function et(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ae(r,e){return r<<32-e|r>>>e}const ar=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function lr(r){for(let e=0;e<r.length;e++)r[e]=cr(r[e]);return r}const Ot=ar?r=>r:lr,ss=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Oe(r){if(F(r),ss)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=dr[r[s]];return e}const de={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nt(r){if(r>=de._0&&r<=de._9)return r-de._0;if(r>=de.A&&r<=de.F)return r-(de.A-10);if(r>=de.a&&r<=de.f)return r-(de.a-10)}function qe(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 o=0,n=0;o<s;o++,n+=2){const i=Nt(r.charCodeAt(n)),a=Nt(r.charCodeAt(n+1));if(i===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}t[o]=i*16+a}return t}function we(...r){let e=0;for(let t=0;t<r.length;t++){const o=r[t];F(o),e+=o.length}const s=new Uint8Array(e);for(let t=0,o=0;t<r.length;t++){const n=r[t];s.set(n,o),o+=n.length}return s}function rs(r,e={}){const s=(o,n)=>r(n).update(o).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=o=>r(o),Object.assign(s,e),Object.freeze(s)}function os(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const ur=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function hr(r,e,s){return r&e^~r&s}function pr(r,e,s){return r&e^r&s^e&s}class fr{constructor(e,s,t,o){S(this,"blockLen");S(this,"outputLen");S(this,"padOffset");S(this,"isLE");S(this,"buffer");S(this,"view");S(this,"finished",!1);S(this,"length",0);S(this,"pos",0);S(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=o,this.buffer=new Uint8Array(e),this.view=et(this.buffer)}update(e){Ae(this),F(e);const{view:s,buffer:t,blockLen:o}=this,n=e.length;for(let i=0;i<n;){const a=Math.min(o-this.pos,n-i);if(a===o){const c=et(e);for(;o<=n-i;i+=o)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(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:o,isLE:n}=this;let{pos:i}=this;s[i++]=128,Te(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(t,0),i=0);for(let u=i;u<o;u++)s[u]=0;t.setBigUint64(o-8,BigInt(this.length*8),n),this.process(t,0);const a=et(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],n)}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:o,finished:n,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=n,e.length=o,e.pos=a,o%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const _e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Me=BigInt(2**32-1),Lt=BigInt(32);function _r(r,e=!1){return e?{h:Number(r&Me),l:Number(r>>Lt&Me)}:{h:Number(r>>Lt&Me)|0,l:Number(r&Me)|0}}function gr(r,e=!1){const s=r.length;let t=new Uint32Array(s),o=new Uint32Array(s);for(let n=0;n<s;n++){const{h:i,l:a}=_r(r[n],e);[t[n],o[n]]=[i,a]}return[t,o]}const xr=(r,e,s)=>r<<s|e>>>32-s,wr=(r,e,s)=>e<<s|r>>>32-s,mr=(r,e,s)=>e<<s-32|r>>>64-s,yr=(r,e,s)=>r<<s-32|e>>>64-s,br=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ge=new Uint32Array(64);class vr extends fr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:o,E:n,F:i,G:a,H:c}=this;return[e,s,t,o,n,i,a,c]}set(e,s,t,o,n,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)ge[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const _=ge[u-15],f=ge[u-2],p=ae(_,7)^ae(_,18)^_>>>3,b=ae(f,17)^ae(f,19)^f>>>10;ge[u]=b+ge[u-7]+p+ge[u-16]|0}let{A:t,B:o,C:n,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const _=ae(a,6)^ae(a,11)^ae(a,25),f=d+_+hr(a,c,l)+br[u]+ge[u]|0,b=(ae(t,2)^ae(t,13)^ae(t,22))+pr(t,o,n)|0;d=l,l=c,c=a,a=i+f|0,i=n,n=o,o=t,t=f+b|0}t=t+this.A|0,o=o+this.B|0,n=n+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,o,n,i,a,c,l,d)}roundClean(){Te(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),Te(this.buffer)}}class Sr extends vr{constructor(){super(32);S(this,"A",_e[0]|0);S(this,"B",_e[1]|0);S(this,"C",_e[2]|0);S(this,"D",_e[3]|0);S(this,"E",_e[4]|0);S(this,"F",_e[5]|0);S(this,"G",_e[6]|0);S(this,"H",_e[7]|0)}}const Er=rs(()=>new Sr,ur(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ut=BigInt(0),it=BigInt(1);function We(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function ns(r){if(typeof r=="bigint"){if(!He(r))throw new Error("positive bigint expected, got "+r)}else pe(r);return r}function $e(r){const e=ns(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===""?ut:BigInt("0x"+r)}function Ye(r){return is(Oe(r))}function as(r){return is(Oe(Ir(F(r)).reverse()))}function ht(r,e){pe(e),r=ns(r);const s=qe(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function cs(r,e){return ht(r,e).reverse()}function Ir(r){return Uint8Array.from(r)}const He=r=>typeof r=="bigint"&&ut<=r;function Ar(r,e,s){return He(r)&&He(e)&&He(s)&&e<=r&&r<s}function Tr(r,e,s,t){if(!Ar(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Cr(r){let e;for(e=0;r>ut;r>>=it,e+=1);return e}const pt=r=>(it<<BigInt(r))-it;function kr(r,e,s){if(pe(r,"hashLen"),pe(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),o=Uint8Array.of(),n=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const u=()=>{c.fill(1),l.fill(0),d=0},_=(...y)=>s(l,we(c,...y)),f=(y=o)=>{l=_(n,y),c=_(),y.length!==0&&(l=_(i,y),c=_())},p=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const E=[];for(;y<e;){c=_();const D=c.slice();E.push(D),y+=c.length}return we(...E)};return(y,E)=>{u(),f(y);let D;for(;!(D=E(p()));)f();return u(),D}}function ft(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(n,i,a){const c=r[n];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${l}`)}const o=(n,i)=>Object.entries(n).forEach(([a,c])=>t(a,c,i));o(e,!1),o(s,!0)}function Dt(r){const e=new WeakMap;return(s,...t)=>{const o=e.get(s);if(o!==void 0)return o;const n=r(s,...t);return e.set(s,n),n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ee=BigInt(0),Z=BigInt(1),be=BigInt(2),ls=BigInt(3),ds=BigInt(4),us=BigInt(5),Rr=BigInt(7),hs=BigInt(8),Pr=BigInt(9),ps=BigInt(16);function ne(r,e){const s=r%e;return s>=ee?s:e+s}function oe(r,e,s){let t=r;for(;e-- >ee;)t*=t,t%=s;return t}function Mt(r,e){if(r===ee)throw new Error("invert: expected non-zero number");if(e<=ee)throw new Error("invert: expected positive modulus, got "+e);let s=ne(r,e),t=e,o=ee,n=Z;for(;s!==ee;){const a=t/s,c=t%s,l=o-n*a;t=s,s=c,o=n,n=l}if(t!==Z)throw new Error("invert: does not exist");return ne(o,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+Z)/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,be),o=r.pow(t,s),n=r.mul(e,o),i=r.mul(r.mul(n,be),o),a=r.mul(n,r.sub(i,r.ONE));return _t(r,a,e),a}function Nr(r){const e=Ze(r),s=_s(r),t=s(e,e.neg(e.ONE)),o=s(e,t),n=s(e,e.neg(t)),i=(r+Rr)/ps;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const u=a.mul(l,o),_=a.mul(l,n),f=a.eql(a.sqr(d),c),p=a.eql(a.sqr(u),c);l=a.cmov(l,d,f),d=a.cmov(_,u,p);const b=a.eql(a.sqr(d),c),y=a.cmov(l,d,b);return _t(a,y,c),y}}function _s(r){if(r<ls)throw new Error("sqrt is not defined for small field");let e=r-Z,s=0;for(;e%be===ee;)e/=be,s++;let t=be;const o=Ze(r);for(;$t(o,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return fs;let n=o.pow(t,e);const i=(e+Z)/be;return function(c,l){if(c.is0(l))return l;if($t(c,l)!==1)throw new Error("Cannot find square root");let d=s,u=c.mul(c.ONE,n),_=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(_,c.ONE);){if(c.is0(_))return c.ZERO;let p=1,b=c.sqr(_);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===d)throw new Error("Cannot find square root");const y=Z<<BigInt(d-p-1),E=c.pow(u,y);d=p,u=c.sqr(E),_=c.mul(_,u),f=c.mul(f,E)}return f}}function Lr(r){return r%ds===ls?fs:r%hs===us?Or:r%ps===Pr?Nr(r):_s(r)}const Dr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Dr.reduce((t,o)=>(t[o]="function",t),e);return ft(r,s),r}function $r(r,e,s){if(s<ee)throw new Error("invalid exponent, negatives unsupported");if(s===ee)return r.ONE;if(s===Z)return e;let t=r.ONE,o=e;for(;s>ee;)s&Z&&(t=r.mul(t,o)),o=r.sqr(o),s>>=Z;return t}function gs(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),n=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),n),t}function $t(r,e){const s=(r.ORDER-Z)/be,t=r.pow(e,s),o=r.eql(t,r.ONE),n=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!o&&!n&&!i)throw new Error("invalid Legendre symbol result");return o?1:n?0:-1}function Br(r,e){e!==void 0&&pe(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ur{constructor(e,s={}){S(this,"ORDER");S(this,"BITS");S(this,"BYTES");S(this,"isLE");S(this,"ZERO",ee);S(this,"ONE",Z);S(this,"_lengths");S(this,"_sqrt");S(this,"_mod");var i;if(e<=ee)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:o,nByteLength:n}=Br(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ne(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ee<=e&&e<this.ORDER}is0(e){return e===ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Z)===Z}neg(e){return ne(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ne(e*e,this.ORDER)}add(e,s){return ne(e+s,this.ORDER)}sub(e,s){return ne(e-s,this.ORDER)}mul(e,s){return ne(e*s,this.ORDER)}pow(e,s){return $r(this,e,s)}div(e,s){return ne(e*Mt(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 Mt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Lr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?cs(e,this.BYTES):ht(e,this.BYTES)}fromBytes(e,s=!1){F(e);const{_lengths:t,BYTES:o,isLE:n,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=n?as(e):Ye(e);if(a&&(c=ne(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return gs(this,e)}cmov(e,s,t){return t?s:e}}function Ze(r,e={}){return new Ur(r,e)}function xs(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 ws(r){const e=xs(r);return e+Math.ceil(e/2)}function Hr(r,e,s=!1){F(r);const t=r.length,o=xs(e),n=ws(e);if(t<16||t<n||t>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+t);const i=s?as(r):Ye(r),a=ne(i,e-Z)+Z;return s?cs(a,o):ht(a,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ce=BigInt(0),ve=BigInt(1);function Ve(r,e){const s=e.negate();return r?s:e}function Bt(r,e){const s=gs(r.Fp,e.map(t=>t.Z));return e.map((t,o)=>r.fromAffine(t.toAffine(s[o])))}function ms(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tt(r,e){ms(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),o=2**r,n=pt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:n,maxNumber:o,shiftBy:i}}function Ut(r,e,s){const{windowSize:t,mask:o,maxNumber:n,shiftBy:i}=s;let a=Number(r&o),c=r>>i;a>t&&(a-=n,c+=ve);const l=e*t,d=l+Math.abs(a)-1,u=a===0,_=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:_,isNegF:f,offsetF:l}}const st=new WeakMap,ys=new WeakMap;function rt(r){return ys.get(r)||1}function Ht(r){if(r!==Ce)throw new Error("invalid wNAF")}class Fr{constructor(e,s){S(this,"BASE");S(this,"ZERO");S(this,"Fn");S(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let o=e;for(;s>Ce;)s&ve&&(t=t.add(o)),o=o.double(),s>>=ve;return t}precomputeWindow(e,s){const{windows:t,windowSize:o}=tt(s,this.bits),n=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,n.push(a);for(let l=1;l<o;l++)a=a.add(i),n.push(a);i=a.double()}return n}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let o=this.ZERO,n=this.BASE;const i=tt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:_,offsetF:f}=Ut(t,a,i);t=c,d?n=n.add(Ve(_,s[f])):o=o.add(Ve(u,s[l]))}return Ht(t),{p:o,f:n}}wNAFUnsafe(e,s,t,o=this.ZERO){const n=tt(e,this.bits);for(let i=0;i<n.windows&&t!==Ce;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Ut(t,i,n);if(t=a,!l){const u=s[c];o=o.add(d?u.negate():u)}}return Ht(t),o}getPrecomputes(e,s,t){let o=st.get(s);return o||(o=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(o=t(o)),st.set(s,o))),o}cached(e,s,t){const o=rt(e);return this.wNAF(o,this.getPrecomputes(o,e,t),s)}unsafe(e,s,t,o){const n=rt(e);return n===1?this._unsafeLadder(e,s,o):this.wNAFUnsafe(n,this.getPrecomputes(n,e,t),s,o)}createCache(e,s){ms(s,this.bits),ys.set(e,s),st.delete(e)}hasCache(e){return rt(e)!==1}}function Gr(r,e,s,t){let o=e,n=r.ZERO,i=r.ZERO;for(;s>Ce||t>Ce;)s&ve&&(n=n.add(o)),t&ve&&(i=i.add(o)),o=o.double(),s>>=ve,t>>=ve;return{p1:n,p2:i}}function Ft(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Mr(e),e}else return Ze(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>Ce))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Ft(e.p,s.Fp,t),n=Ft(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!o.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:o,Fn:n}}function Wr(r,e){return function(t){const o=r(t);return{secretKey:o,publicKey:e(o)}}}class bs{constructor(e,s){S(this,"oHash");S(this,"iHash");S(this,"blockLen");S(this,"outputLen");S(this,"finished",!1);S(this,"destroyed",!1);if(es(e),F(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,o=new Uint8Array(t);o.set(s.length>t?e.create().update(s).digest():s);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),Te(o)}update(e){return Ae(this),this.iHash.update(e),this}digestInto(e){Ae(this),F(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:o,destroyed:n,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=n,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 Gt=(r,e)=>(r+(r>=0?e:-e)/Ss)/e;function Vr(r,e,s){const[[t,o],[n,i]]=e,a=Gt(i*r,s),c=Gt(-o*r,s);let l=r-a*t-c*n,d=-a*o-c*i;const u=l<ue,_=d<ue;u&&(l=-l),_&&(d=-d);const f=pt(Math.ceil(Cr(s)/2))+Ie;if(l<ue||l>=f||d<ue||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:_,k2:d}}function at(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ot(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return We(s.lowS,"lowS"),We(s.prehash,"prehash"),s.format!==void 0&&at(s.format),s}class Kr extends Error{constructor(e=""){super(e)}}const xe={Err:Kr,_tlv:{encode:(r,e)=>{const{Err:s}=xe;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,o=$e(t);if(o.length/2&128)throw new s("tlv.encode: long form length too big");const n=t>127?$e(o.length/2|128):"";return $e(r)+n+o+e},decode(r,e){const{Err:s}=xe;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 o=e[t++],n=!!(o&128);let i=0;if(!n)i=o;else{const c=o&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}=xe;if(r<ue)throw new e("integer: negative integers are not allowed");let s=$e(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}=xe;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}=xe,o=F(r,void 0,"signature"),{v:n,l:i}=t.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,n),{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}=xe,t=e.encode(2,s.encode(r.r)),o=e.encode(2,s.encode(r.s)),n=t+o;return e.encode(48,n)}},ue=BigInt(0),Ie=BigInt(1),Ss=BigInt(2),Be=BigInt(3),jr=BigInt(4);function zr(r,e={}){const s=qr("weierstrass",r,e),{Fp:t,Fn:o}=s;let n=s.CURVE;const{h:i,n:a}=n;ft(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(n.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Is(t,o);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,x,w){const{x:v,y:A}=x.toAffine(),k=t.toBytes(v);if(We(w,"isCompressed"),w){d();const C=!t.isOdd(A);return we(Es(C),k)}else return we(Uint8Array.of(4),k,t.toBytes(A))}function _(L){F(L,void 0,"Point");const{publicKey:x,publicKeyUncompressed:w}=l,v=L.length,A=L[0],k=L.subarray(1);if(v===x&&(A===2||A===3)){const C=t.fromBytes(k);if(!t.isValid(C))throw new Error("bad point: is not on curve, wrong x");const R=b(C);let I;try{I=t.sqrt(R)}catch(W){const H=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}d();const P=t.isOdd(I);return(A&1)===1!==P&&(I=t.neg(I)),{x:C,y:I}}else if(v===w&&A===4){const C=t.BYTES,R=t.fromBytes(k.subarray(0,C)),I=t.fromBytes(k.subarray(C,C*2));if(!y(R,I))throw new Error("bad point: is not on curve");return{x:R,y:I}}else throw new Error(`bad point: got length ${v}, expected compressed=${x} or uncompressed=${w}`)}const f=e.toBytes||u,p=e.fromBytes||_;function b(L){const x=t.sqr(L),w=t.mul(x,L);return t.add(t.add(w,t.mul(L,n.a)),n.b)}function y(L,x){const w=t.sqr(x),v=b(L);return t.eql(w,v)}if(!y(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(n.a,Be),jr),D=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(E,D)))throw new Error("bad curve params: a or b");function U(L,x,w=!1){if(!t.isValid(x)||w&&t.is0(x))throw new Error(`bad point coordinate ${L}`);return x}function M(L){if(!(L instanceof J))throw new Error("Weierstrass Point expected")}function B(L){if(!c||!c.basises)throw new Error("no endo");return Vr(L,c.basises,o.ORDER)}const K=Dt((L,x)=>{const{X:w,Y:v,Z:A}=L;if(t.eql(A,t.ONE))return{x:w,y:v};const k=L.is0();x==null&&(x=k?t.ONE:t.inv(A));const C=t.mul(w,x),R=t.mul(v,x),I=t.mul(A,x);if(k)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:C,y:R}}),le=Dt(L=>{if(L.is0()){if(e.allowInfinityPoint&&!t.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x,y:w}=L.toAffine();if(!t.isValid(x)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!y(x,w))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function fe(L,x,w,v,A){return w=new J(t.mul(w.X,L),w.Y,w.Z),x=Ve(v,x),w=Ve(A,w),x.add(w)}const $=class ${constructor(x,w,v){S(this,"X");S(this,"Y");S(this,"Z");this.X=U("x",x),this.Y=U("y",w,!0),this.Z=U("z",v),Object.freeze(this)}static CURVE(){return n}static fromAffine(x){const{x:w,y:v}=x||{};if(!x||!t.isValid(w)||!t.isValid(v))throw new Error("invalid affine point");if(x instanceof $)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(v)?$.ZERO:new $(w,v,t.ONE)}static fromBytes(x){const w=$.fromAffine(p(F(x,void 0,"point")));return w.assertValidity(),w}static fromHex(x){return $.fromBytes(qe(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,w=!0){return ie.createCache(this,x),w||this.multiply(Be),this}assertValidity(){le(this)}hasEvenY(){const{y:x}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(x)}equals(x){M(x);const{X:w,Y:v,Z:A}=this,{X:k,Y:C,Z:R}=x,I=t.eql(t.mul(w,R),t.mul(k,A)),P=t.eql(t.mul(v,R),t.mul(C,A));return I&&P}negate(){return new $(this.X,t.neg(this.Y),this.Z)}double(){const{a:x,b:w}=n,v=t.mul(w,Be),{X:A,Y:k,Z:C}=this;let R=t.ZERO,I=t.ZERO,P=t.ZERO,N=t.mul(A,A),W=t.mul(k,k),H=t.mul(C,C),O=t.mul(A,k);return O=t.add(O,O),P=t.mul(A,C),P=t.add(P,P),R=t.mul(x,P),I=t.mul(v,H),I=t.add(R,I),R=t.sub(W,I),I=t.add(W,I),I=t.mul(R,I),R=t.mul(O,R),P=t.mul(v,P),H=t.mul(x,H),O=t.sub(N,H),O=t.mul(x,O),O=t.add(O,P),P=t.add(N,N),N=t.add(P,N),N=t.add(N,H),N=t.mul(N,O),I=t.add(I,N),H=t.mul(k,C),H=t.add(H,H),N=t.mul(H,O),R=t.sub(R,N),P=t.mul(H,W),P=t.add(P,P),P=t.add(P,P),new $(R,I,P)}add(x){M(x);const{X:w,Y:v,Z:A}=this,{X:k,Y:C,Z:R}=x;let I=t.ZERO,P=t.ZERO,N=t.ZERO;const W=n.a,H=t.mul(n.b,Be);let O=t.mul(w,k),V=t.mul(v,C),z=t.mul(A,R),se=t.add(w,v),G=t.add(k,C);se=t.mul(se,G),G=t.add(O,V),se=t.sub(se,G),G=t.add(w,A);let Y=t.add(k,R);return G=t.mul(G,Y),Y=t.add(O,z),G=t.sub(G,Y),Y=t.add(v,A),I=t.add(C,R),Y=t.mul(Y,I),I=t.add(V,z),Y=t.sub(Y,I),N=t.mul(W,G),I=t.mul(H,z),N=t.add(I,N),I=t.sub(V,N),N=t.add(V,N),P=t.mul(I,N),V=t.add(O,O),V=t.add(V,O),z=t.mul(W,z),G=t.mul(H,G),V=t.add(V,z),z=t.sub(O,z),z=t.mul(W,z),G=t.add(G,z),O=t.mul(V,G),P=t.add(P,O),O=t.mul(Y,G),I=t.mul(se,I),I=t.sub(I,O),O=t.mul(se,V),N=t.mul(Y,N),N=t.add(N,O),new $(I,P,N)}subtract(x){return this.add(x.negate())}is0(){return this.equals($.ZERO)}multiply(x){const{endo:w}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let v,A;const k=C=>ie.cached(this,C,R=>Bt($,R));if(w){const{k1neg:C,k1:R,k2neg:I,k2:P}=B(x),{p:N,f:W}=k(R),{p:H,f:O}=k(P);A=W.add(O),v=fe(w.beta,N,H,C,I)}else{const{p:C,f:R}=k(x);v=C,A=R}return Bt($,[v,A])[0]}multiplyUnsafe(x){const{endo:w}=e,v=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===ue||v.is0())return $.ZERO;if(x===Ie)return v;if(ie.hasCache(this))return this.multiply(x);if(w){const{k1neg:A,k1:k,k2neg:C,k2:R}=B(x),{p1:I,p2:P}=Gr($,v,k,R);return fe(w.beta,I,P,A,C)}else return ie.unsafe(v,x)}toAffine(x){return K(this,x)}isTorsionFree(){const{isTorsionFree:x}=e;return i===Ie?!0:x?x($,this):ie.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=e;return i===Ie?this:x?x($,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return We(x,"isCompressed"),this.assertValidity(),f($,this,x)}toHex(x=!0){return Oe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};S($,"BASE",new $(n.Gx,n.Gy,t.ONE)),S($,"ZERO",new $(t.ZERO,t.ONE,t.ZERO)),S($,"Fp",t),S($,"Fn",o);let J=$;const me=o.BITS,ie=new Fr(J,e.endo?Math.ceil(me/2):me);return J.BASE.precompute(8),J}function Es(r){return Uint8Array.of(r?2:3)}function Is(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yr(r,e={}){const{Fn:s}=r,t=e.randomBytes||os,o=Object.assign(Is(r.Fp,s),{seed:ws(s.ORDER)});function n(f){try{const p=s.fromBytes(f);return s.isValidNot0(p)}catch{return!1}}function i(f,p){const{publicKey:b,publicKeyUncompressed:y}=o;try{const E=f.length;return p===!0&&E!==b||p===!1&&E!==y?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=t(o.seed)){return Hr(F(f,o.seed,"seed"),s.ORDER)}function c(f,p=!0){return r.BASE.multiply(s.fromBytes(f)).toBytes(p)}function l(f){const{secretKey:p,publicKey:b,publicKeyUncompressed:y}=o;if(!dt(f)||"_lengths"in s&&s._lengths||p===b)return;const E=F(f,void 0,"key").length;return E===b||E===y}function d(f,p,b=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(f);return r.fromBytes(p).multiply(y).toBytes(b)}const u={isValidSecretKey:n,isValidPublicKey:i,randomSecretKey:a},_=Wr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:_,Point:r,utils:u,lengths:o})}function Zr(r,e,s={}){es(e),ft(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||os,o=s.hmac||((x,w)=>vs(e,x,w)),{Fp:n,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:_,lengths:f}=Yr(r,s),p={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*Ss<n.ORDER;function y(x){const w=a>>Ie;return x>w}function E(x,w){if(!i.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function D(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(x,w){at(w);const v=f.signature,A=w==="compact"?v:w==="recovered"?v+1:void 0;return F(x,A)}class M{constructor(w,v,A){S(this,"r");S(this,"s");S(this,"recovery");if(this.r=E("r",w),this.s=E("s",v),A!=null){if(D(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(w,v=p.format){U(w,v);let A;if(v==="der"){const{r:I,s:P}=xe.toSig(F(w));return new M(I,P)}v==="recovered"&&(A=w[0],v="compact",w=w.subarray(1));const k=f.signature/2,C=w.subarray(0,k),R=w.subarray(k,k*2);return new M(i.fromBytes(C),i.fromBytes(R),A)}static fromHex(w,v){return this.fromBytes(qe(w),v)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new M(this.r,this.s,w)}recoverPublicKey(w){const{r:v,s:A}=this,k=this.assertRecovery(),C=k===2||k===3?v+a:v;if(!n.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const R=n.toBytes(C),I=r.fromBytes(we(Es((k&1)===0),R)),P=i.inv(C),N=K(F(w,void 0,"msgHash")),W=i.create(-N*P),H=i.create(A*P),O=r.BASE.multiplyUnsafe(W).add(I.multiplyUnsafe(H));if(O.is0())throw new Error("invalid recovery: point at infinify");return O.assertValidity(),O}hasHighS(){return y(this.s)}toBytes(w=p.format){if(at(w),w==="der")return qe(xe.hexFromSig(this));const{r:v,s:A}=this,k=i.toBytes(v),C=i.toBytes(A);return w==="recovered"?(D(),we(Uint8Array.of(this.assertRecovery()),k,C)):we(k,C)}toHex(w){return Oe(this.toBytes(w))}}const B=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const v=Ye(w),A=w.length*8-c;return A>0?v>>BigInt(A):v},K=s.bits2int_modN||function(w){return i.create(B(w))},le=pt(c);function fe(x){return Tr("num < 2^"+c,x,ue,le),i.toBytes(x)}function J(x,w){return F(x,void 0,"message"),w?F(e(x),void 0,"prehashed message"):x}function me(x,w,v){const{lowS:A,prehash:k,extraEntropy:C}=ot(v,p);x=J(x,k);const R=K(x),I=i.fromBytes(w);if(!i.isValidNot0(I))throw new Error("invalid private key");const P=[fe(I),fe(R)];if(C!=null&&C!==!1){const O=C===!0?t(f.secretKey):C;P.push(F(O,void 0,"extraEntropy"))}const N=we(...P),W=R;function H(O){const V=B(O);if(!i.isValidNot0(V))return;const z=i.inv(V),se=r.BASE.multiply(V).toAffine(),G=i.create(se.x);if(G===ue)return;const Y=i.create(z*i.create(W+G*I));if(Y===ue)return;let bt=(se.x===G?0:2)|Number(se.y&Ie),vt=Y;return A&&y(Y)&&(vt=i.neg(Y),bt^=1),new M(G,vt,b?void 0:bt)}return{seed:N,k2sig:H}}function ie(x,w,v={}){const{seed:A,k2sig:k}=me(x,w,v);return kr(e.outputLen,i.BYTES,o)(A,k).toBytes(v.format)}function $(x,w,v,A={}){const{lowS:k,prehash:C,format:R}=ot(A,p);if(v=F(v,void 0,"publicKey"),w=J(w,C),!dt(x)){const I=x instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+I)}U(x,R);try{const I=M.fromBytes(x,R),P=r.fromBytes(v);if(k&&I.hasHighS())return!1;const{r:N,s:W}=I,H=K(w),O=i.inv(W),V=i.create(H*O),z=i.create(N*O),se=r.BASE.multiplyUnsafe(V).add(P.multiplyUnsafe(z));return se.is0()?!1:i.create(se.x)===N}catch{return!1}}function L(x,w,v={}){const{prehash:A}=ot(v,p);return w=J(w,A),M.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:_,lengths:f,Point:r,sign:ie,verify:$,recoverPublicKey:L,Signature:M,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")]]},qt=BigInt(2);function Jr(r){const e=gt.p,s=BigInt(3),t=BigInt(6),o=BigInt(11),n=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=oe(d,s,e)*d%e,_=oe(u,s,e)*d%e,f=oe(_,qt,e)*l%e,p=oe(f,o,e)*f%e,b=oe(p,n,e)*p%e,y=oe(b,a,e)*b%e,E=oe(y,c,e)*y%e,D=oe(E,a,e)*b%e,U=oe(D,s,e)*d%e,M=oe(U,i,e)*p%e,B=oe(M,t,e)*l%e,K=oe(B,qt,e);if(!ct.eql(ct.sqr(K),r))throw new Error("Cannot find square root");return K}const ct=Ze(gt.p,{sqrt:Jr}),Qr=zr(gt,{Fp:ct,endo:Xr}),eo=Zr(Qr,Er),to=BigInt(0),ke=BigInt(1),so=BigInt(2),ro=BigInt(7),oo=BigInt(256),no=BigInt(113),As=[],Ts=[],Cs=[];for(let r=0,e=ke,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],As.push(2*(5*t+s)),Ts.push((r+1)*(r+2)/2%64);let o=to;for(let n=0;n<7;n++)e=(e<<ke^(e>>ro)*no)%oo,e&so&&(o^=ke<<(ke<<BigInt(n))-ke);Cs.push(o)}const ks=gr(Cs,!0),io=ks[0],ao=ks[1],Wt=(r,e,s)=>s>32?mr(r,e,s):xr(r,e,s),Vt=(r,e,s)=>s>32?yr(r,e,s):wr(r,e,s);function co(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],u=Wt(l,d,1)^s[a],_=Vt(l,d,1)^s[a+1];for(let f=0;f<50;f+=10)r[i+f]^=u,r[i+f+1]^=_}let o=r[2],n=r[3];for(let i=0;i<24;i++){const a=Ts[i],c=Wt(o,n,a),l=Vt(o,n,a),d=As[i];o=r[d],n=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]^=io[t],r[1]^=ao[t]}Te(s)}class xt{constructor(e,s,t,o=!1,n=24){S(this,"state");S(this,"pos",0);S(this,"posOut",0);S(this,"finished",!1);S(this,"state32");S(this,"destroyed",!1);S(this,"blockLen");S(this,"suffix");S(this,"outputLen");S(this,"enableXOF",!1);S(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=o,this.rounds=n,pe(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ir(this.state)}clone(){return this._cloneInto()}keccak(){Ot(this.state32),co(this.state32,this.rounds),Ot(this.state32),this.posOut=0,this.pos=0}update(e){Ae(this),F(e);const{blockLen:s,state:t}=this,o=e.length;for(let n=0;n<o;){const i=Math.min(s-this.pos,o-n);for(let a=0;a<i;a++)t[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:o}=this;e[t]^=s,s&128&&t===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){Ae(this,!1),F(e),this.finish();const s=this.state,{blockLen:t}=this;for(let o=0,n=e.length;o<n;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,n-o);e.set(s.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=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 pe(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,Te(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:o,rounds:n,enableXOF:i}=this;return e||(e=new xt(s,t,o,i,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=t,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}const lo=(r,e,s,t={})=>rs(()=>new xt(e,r,s),t),Kt=lo(1,136,32);class uo{async verifyJWT(e,s){try{const t=this.decodeJWT(e);h.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const o=Math.floor(Date.now()/1e3);return t.exp&&t.exp<o?(h.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:o,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(h.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(h.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw h.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ls.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),o=new TextEncoder().encode(`Ethereum Signed Message:
|
|
2
|
-
${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);const i=Kt(n),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=ho(a),l=c.slice(0,32),d=c.slice(32,64),u=c[64],_=u>=27?u-27:u,b=new eo.Signature(jt(l),jt(d)).addRecoveryBit(_).recoverPublicKey(i).toBytes(!1).slice(1),y=Kt(b);return"0x"+Oe(y.slice(12))}}function ho(r){const e=new Uint8Array(r.length/2);for(let s=0;s<e.length;s++)e[s]=parseInt(r.substring(s*2,s*2+2),16);return e}function jt(r){let e="0x";for(const s of r)e+=s.toString(16).padStart(2,"0");return BigInt(e)}const po=3e4;class fo{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??po);try{const o=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 n;const i=await o.text();try{n=i?JSON.parse(i):null}catch{n={_raw:i}}return{status:o.status,data:n,headers:Object.fromEntries(o.headers.entries())}}finally{clearTimeout(t)}}}class wt{static generateState(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}openAuth(e){return new Promise((s,t)=>{const o=Math.max(e.width??500,500),n=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-o)/2,a=window.screenY+(window.outerHeight-n)/2,c=wt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,u=window.open(d,"CROSSx OAuth",`width=${o},height=${n},left=${i},top=${a}`);if(!u){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const _=setTimeout(()=>{h.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),U(),t(new Error("Authentication timeout"))},5*60*1e3),f=10,p=30;let b=0,y=null;const E=()=>{clearInterval(D),h.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+p+"초간 대기합니다"),y=setTimeout(()=>{U(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},p*1e3)},D=setInterval(()=>{b++;try{u.closed&&(b<=f?E():(U(),t(new Error("로그인이 취소되었습니다"))))}catch{E()}},1e3),U=()=>{clearTimeout(_),clearInterval(D),y&&clearTimeout(y),window.removeEventListener("message",M)},M=B=>{var le,fe,J,me,ie,$,L;if(B.origin!==e.expectedOrigin)return;U(),h.log("[CROSSx] OAuth postMessage 수신 — status:",B.data.status);const K=B.data.state??((le=B.data.data)==null?void 0:le.state);if(!K||K!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(B.data.status==="success"){const x=((fe=B.data.data)==null?void 0:fe.accessToken)||((J=B.data.data)==null?void 0:J.idToken);h.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((me=B.data.data)!=null&&me.accessToken),hasIdToken:!!((ie=B.data.data)!=null&&ie.idToken)}),x?s(x):(h.error("[CROSSx] 토큰을 찾을 수 없음:",B.data),t(new Error("Token not found in response")))}else h.error("[CROSSx] OAuth 실패:",($=B.data.data)==null?void 0:$.error),t(new Error(((L=B.data.data)==null?void 0:L.error)||"Authentication failed"))};window.addEventListener("message",M)})}}const Re="crossx_wallet_data",Ee="crossx_mock_pw_hash";class _o{constructor(e,s){this.storage=e,this.passwordStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return h.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Re)?"exists":"not_found";return h.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Re);if(t)return t;const o={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Re,o);const n=(s=this.passwordStore)==null?void 0:s.get();return n&&(await this.storage.set(Ee,n),h.log("[Mock] 지갑 생성 — 비밀번호 저장됨")),o}catch(t){throw new m(g.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Re);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 h.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,o=0,n,i){return h.log(`[Mock] signMessage chainId=${s} index=${o} uuid=${n} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,o=0,n,i){return h.log(`[Mock] signTypedData chainId=${s} index=${o} uuid=${n} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,o=0,n){h.log(`[Mock] signTransaction chainId=${s} index=${o} uuid=${n}:`,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,o){return h.log(`[Mock] sendTransaction chainId=${s} uuid=${o}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPassword(e){var t;if(h.log("[Mock] verifyPassword"),this.passwordScenario==="wrong")return!1;const s=await this.storage.get(Ee);return s&&s!==e?!1:(s||await this.storage.set(Ee,e),(t=this.passwordStore)==null||t.set(e),h.log("[Mock] verifyPassword → 성공"),!0)}async changePassword(e,s){var n;if(h.log("[Mock] changePassword"),this.passwordScenario==="wrong")throw new m(g.PASSWORD_WRONG,"Incorrect password.");const t=(n=this.passwordStore)==null?void 0:n.get(),o=await this.storage.get(Ee);if(o&&t&&o!==t)throw new m(g.PASSWORD_WRONG,"Incorrect password.");await this.storage.set(Ee,s),h.log("[Mock] changePassword 완료")}async migrateWallet(e,s){var n;if(h.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new m(g.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new m(g.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(Re,t);const o=(n=this.passwordStore)==null?void 0:n.get();return o&&(await this.storage.set(Ee,o),h.log("[Mock] 마이그레이션 — 비밀번호 저장됨")),t}async getShareC(){return h.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyPin(e,s){return h.log("[Mock] verifyPin"),{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 Ke{constructor(e,s,t,o,n){this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=o,this.passwordStore=n??null}getPassword(){var e;return((e=this.passwordStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new m(g.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const o=this.getAuthToken(),n=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:n,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const u=d.message||d.data||"API 요청에 실패했습니다";h.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:u,url:n,method:e,fullResponse:d});const _=Ke.mapGatewayError(d.code,d.data),f=Ke.getGatewayErrorMessage(d.code,u),p=new m(_,f,d.data??void 0);throw p.gatewayCode=d.code,p.gatewayMessage=u,p}return h.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:n,method:e}),d.data??d}return d}catch(l){if(l instanceof m)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,u=d.message||d.data||"API 요청에 실패했습니다",_=d.code||"UNKNOWN";throw h.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:_,message:u,url:n,method:e,status:(c=l.response)==null?void 0:c.status}),new m(g.UNKNOWN_ERROR,`Wallet Gateway 오류 (${_}): ${u}`)}throw l}}async checkWallet(){h.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return h.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,h.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(h.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw h.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new m(g.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){h.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const n=await this.getAddress(e,0);return h.log("[CROSSx] 주소 조회 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}h.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePassword()},o=await this.request("POST","/mnemonic/create",t);return h.log("[CROSSx] /mnemonic/create 완료 — address:",o.address),{id:e,address:o.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.requirePassword(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new m(g.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new m(g.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new m(g.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const o={action:e,params:t},n=await this.request("POST","/mnemonic/prepare",o);return{uuid:n.uuid,expiresAt:n.expiresAt}}async signMessage(e,s,t,o,n,i){const a={message:t};n&&(a.uuid=n),i&&(a.from=i);const c=this.getPassword();c&&(a.password=c);const l=await this.request("POST","/mnemonic/sign-message",a);return{chainId:s,signature:l.signature,format:"hex"}}async signTypedData(e,s,t,o,n,i){const a={typedData:t};n&&(a.uuid=n),i&&(a.from=i);const c=this.getPassword();c&&(a.password=c);const l=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(s)}`,a);return{chainId:s,signature:l.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,o,n){const i={unsignedTx:this.buildUnsignedTx(t)};n&&(i.uuid=n);const a=this.getPassword();a&&(i.password=a);const c=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(s)}`,i);return{chainId:s,signature:c.signedTx,txHash:c.txHash,format:"hex"}}async sendTransaction(e,s,t,o){const n={unsignedTx:this.buildUnsignedTx(t)};o&&(n.uuid=o);const i=this.getPassword();return i&&(n.password=i),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,n)).txHash}}async migrateWallet(e,s){h.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={pin:e,sub:s,password:this.requirePassword()},o=await this.request("POST","/mnemonic/migrate",t);return h.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",o.address),{id:s,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePassword()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPassword(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).verified}async changePassword(e,s){const t={password:this.requirePassword(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePassword()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyPin(e,s){const t={pin:e,sub:s};return this.request("POST","/mnemonic/verify-pin",t)}requirePassword(){const e=this.getPassword();if(!e)throw new m(g.PASSWORD_NOT_SET,"비밀번호가 설정되지 않았습니다. 비밀번호를 입력해 주세요.");return e}static mapGatewayError(e,s){switch(e){case-10002:return g.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return g.UNKNOWN_ERROR;case-10006:return g.GATEWAY_INTERNAL_ERROR;case-10008:return g.GATEWAY_LOCK_CONFLICT;case-10010:return g.MIGRATION_FAILED;case-10012:return g.MIGRATION_BACKUP_EXISTS;case-10027:return g.MIGRATION_PIN_LOCKED;case-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.ORIGIN_NOT_ALLOWED;case-10028:return g.PASSWORD_WRONG;case-10029:return g.PASSWORD_COMPLEXITY;case-10026:return g.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return g.PREPARE_FAILED;case-10016:return g.PREPARE_EXPIRED;case-10017:case-10018:return g.PREPARE_MISMATCH;default:return g.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 password. Please try again.";case-10029:return"Password does not meet complexity requirements. Please use a stronger password.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";default:return`Request failed (${e}): ${s}`}}}class Pe{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=Pe.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(o=>o.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?tr:er;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new m(Pe.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Pe.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new m(g.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(ze).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return g.CHAIN_NOT_SUPPORTED;case-10021:return g.INVALID_CHAIN;case-10022:return g.PROJECT_NOT_REGISTERED;case-10023:return g.PROJECT_ID_MISSING;case-10024:return g.APP_IDENTIFIER_MISSING;case-10025:return g.INVALID_APP_TYPE;default:return g.UNKNOWN_ERROR}}}const zt="__crossx-confirm-style",j="__crossx-confirm-overlay",go={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 Yt(r,e){const s=go[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 xo=`
|
|
1
|
+
"use strict";var Os=Object.defineProperty;var Ns=(r,e,s)=>e in r?Os(r,e,{enumerable:!0,configurable:!0,writable:!0,value:s}):r[e]=s;var S=(r,e,s)=>Ns(r,typeof e!="symbol"?e+"":e,s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ls=require("jose");var _=(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.PASSWORD_NOT_SET="PASSWORD_NOT_SET",r.PASSWORD_WRONG="PASSWORD_WRONG",r.PASSWORD_COMPLEXITY="PASSWORD_COMPLEXITY",r.PASSWORD_CANCELLED="PASSWORD_CANCELLED",r.INVALID_CONFIG="INVALID_CONFIG",r.UNKNOWN_ERROR="UNKNOWN_ERROR",r))(_||{});class m extends Error{constructor(e,s,t){super(s),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,m.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const 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}},Ds=Object.fromEntries(Object.entries(je).map(([r,e])=>[r,e.caipId])),Ms=new Map(Object.values(je).map(r=>[r.caipId,r]));new Map(Object.values(je).map(r=>[r.chainId,r]));const $s={symbol:"",decimals:18};function Je(r){var e;return((e=Ms.get(r))==null?void 0:e.nativeCurrency)??$s}class Xt{constructor(e,s){this.sdk=e,this.chainId=s,this._listeners=new Map}async request({method:e,params:s=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(s[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new m(_.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new m(_.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(o=>o(...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 ye=null;function St(r){ye=r}const h={log(...r){if(ye){ye.log(...r);return}},warn(...r){if(ye){ye.warn(...r);return}},error(...r){if(ye){ye.error(...r);return}}},Bs={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:"건너뛰기",pinInput_title:"PIN 입력",pinInput_placeholder:"4자리 PIN을 입력하세요",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",passwordNotice_headerSubtitle:"트랜잭션, PK/니모닉 및 계정 삭제 시 필요합니다.",passwordNotice_title:"비밀번호 설정 주의사항",passwordNotice_description:"보안을 위해 이 비밀번호는 재설정하거나 복구할 수 없습니다. 반드시 백업하거나 암기해 두시기 바랍니다.",passwordNotice_check1:"이 비밀번호는 분실 시 복구할 수 없으며, 안전하게 백업해 두었습니다.",passwordNotice_check2:"비밀번호 분실 시 계정 및 모든 관련 데이터에 영구적으로 접근이 불가능해질 수 있습니다.",passwordNotice_check3:"지원팀을 포함한 제3자는 이 비밀번호를 복구하거나 재설정해 줄 수 없습니다.",passwordNotice_nextButton:"다음",passwordNotice_submitButton:"동의합니다",passwordSetup_title:"비밀번호 만들기",passwordSetup_subtitle:"비밀번호는 자산 전송 시에만 사용됩니다.",passwordSetup_newPasswordLabel:"새 비밀번호",passwordSetup_confirmPasswordLabel:"새 비밀번호 확인",passwordSetup_rule_minLength:"8자 이상",passwordSetup_rule_uppercase:"대문자 1자 이상 포함",passwordSetup_rule_number:"숫자 1자 이상 포함",passwordSetup_rule_special:"특수문자 1자 이상 포함",passwordSetup_confirmError:"비밀번호가 일치하지 않습니다",passwordSetup_submitButton:"다음",passwordInput_title:"비밀번호 입력",passwordInput_subtitle:"계속하려면 비밀번호를 입력하세요.",passwordInput_passwordLabel:"비밀번호",passwordInput_submitButton:"확인",passwordInput_error:"비밀번호가 올바르지 않습니다. 다시 시도해 주세요.",verifyPassword_title:"비밀번호 확인",verifyPassword_subtitle:"계속하려면 현재 비밀번호를 확인해 주세요.",verifyPassword_passwordLabel:"비밀번호 확인"},Jt={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",pinInput_title:"Enter PIN",pinInput_placeholder:"Enter your 4-digit PIN",pinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",passwordNotice_headerSubtitle:"Required for Transactions, PK/Mnemonic & Account Deletion.",passwordNotice_title:"Password Setup Notice",passwordNotice_description:"For your security, this password cannot be reset or recovered. Please ensure you have it backed up or memorized.",passwordNotice_check1:"This password cannot be recovered if lost, and I have securely backed it up.",passwordNotice_check2:"Losing this password may result in permanent loss of access to my account and all associated data.",passwordNotice_check3:"No third party, including the support team, can recover or reset this password on my behalf.",passwordNotice_nextButton:"Next",passwordNotice_submitButton:"I Understand",passwordSetup_title:"Create Password",passwordSetup_subtitle:"Password is only used to transfer your asset.",passwordSetup_newPasswordLabel:"New Password",passwordSetup_confirmPasswordLabel:"Confirm New Password",passwordSetup_rule_minLength:"Over 8 letters",passwordSetup_rule_uppercase:"Include at least 1 uppercase letter",passwordSetup_rule_number:"Include at least 1 number",passwordSetup_rule_special:"Include at least 1 special character",passwordSetup_confirmError:"Password is incorrect",passwordSetup_submitButton:"Next",passwordInput_title:"Enter Password",passwordInput_subtitle:"Enter your password to continue.",passwordInput_passwordLabel:"Password",passwordInput_submitButton:"Confirm",passwordInput_error:"Incorrect password. Please try again.",verifyPassword_title:"Verify Your Password",verifyPassword_subtitle:"To continue, please confirm your current password",verifyPassword_passwordLabel:"Confirm Password"},Us={ko:Bs,en:Jt};function Et(r="en",e){return Us[r]??Jt}const Qe="crossx_access_token",Ne="crossx_refresh_token",Le="crossx_user_info";class Hs{constructor(e,s,t,o,n,i,a){this.config=e,this.storage=s,this.crypto=t,this.oauth=o,this.transport=n,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 m(_.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 o=t;if(o.code&&o.code!==200&&o.code>0)throw new m(_.AUTH_FAILED,`${s} 실패 (코드 ${o.code}): ${o.message}`)}}async execute(e){var o,n,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:u}=this.config,g=`${d}${l}`;h.log(`[CROSSx] OAuth 팝업 열기 (${c||"일반"} 로그인)`);const f=await this.oauth.openAuth({authUrl:g,expectedOrigin:new URL(d).origin});h.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",f.length,")");const{accessToken:p,refreshToken:b}=await this.exchangeFirebaseToken(f,u);let y,E;try{const U=this.crypto.decodeJWT(f);E=(o=U.firebase)==null?void 0:o.sign_in_provider;const M=((n=U.firebase)==null?void 0:n.identities)??{};E==="google.com"?y=(i=M["google.com"])==null?void 0:i[0]:E==="apple.com"&&(y=(a=M["apple.com"])==null?void 0:a[0]),h.log("[CROSSx] OAuth provider sub 추출 — provider:",E,"hasProviderSub:",!!y)}catch{h.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(p){const U=this.crypto.decodeJWT(p);h.log("[CROSSx] access_token 디코딩 — sub:",U.sub,"exp:",U.exp);const M=await this.crypto.verifyJWT(p);if(t=M.signatureVerified??!1,!M.valid)throw h.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const B=M.payload;s={id:B.sub,email:B.email,signInProvider:E,providerSub:y},this.tokenStore.set(p),this.useCookieAuth||(await this.storage.set(Qe,p),b&&await this.storage.set(Ne,b))}else{const U=this.crypto.decodeJWT(f);s={id:U.sub,email:U.email,signInProvider:E,providerSub:y},h.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",s.id)}h.log("[CROSSx] 사용자 정보 — id:",s.id);const D=this.useCookieAuth?{id:s.id,signInProvider:s.signInProvider,providerSub:s.providerSub}:s;await this.storage.set(Le,D),h.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(c){return h.error("[CROSSx] SignIn 에러 (OAuth/토큰 교환 단계):",c),{success:!1,error:c instanceof Error?c.message:"Sign in failed"}}return h.log("[CROSSx][Migration Phase 1] OAuth 로그인 완료, 지갑 로드 시작 — userId:",s.id),this.loadWallet(s,t)}async exchangeFirebaseToken(e,s){const t=this.useCookieAuth,o=t?`${s}/cross-auth/social/login/cookie`:`${s}/cross-auth/social/login`;h.log("[CROSSx] Firebase 토큰 교환 요청");const n=await this.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});h.log("[CROSSx] 토큰 교환 응답 — status:",n.status);const i=n.data;this.checkResponseError(i,"Token exchange");const a=this.extractAccessToken(i);if(t&&!a)return h.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new m(_.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");h.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 n=t.data,i=n.access_token??n.token;if(typeof i=="string")return i}const o=t.access_token??t.token;if(typeof o=="string")return o}}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 n=t.data,i=n.refresh_token??n.refresh;if(typeof i=="string")return i}const o=t.refresh_token??t.refresh;if(typeof o=="string")return o}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 o=await this.storage.get(Le);if(o)return h.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(o,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){h.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(Qe),o=await this.storage.get(Ne);if(h.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",o?"있음":"없음"),!o)return h.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const n=await this.silentRefresh(o);h.log("[CROSSx] restoreSession — silentRefresh 결과:",n?"토큰 발급 성공":"토큰 없음"),n&&this.tokenStore.set(n)}const s=await this.storage.get(Le);if(h.log("[CROSSx] restoreSession — userInfo 조회:",s?`있음 (id: ${s.id})`:"없음"),!s)return null;h.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",s.id);try{return await this.loadWallet(s,!1)}catch(t){return h.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:s,tokenSignatureVerified:!1}}}catch(e){return h.log("[CROSSx] restoreSession — 세션 복원 실패, 스토리지 정리:",e),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(Ne),await this.storage.remove(Le),null}}silentRefresh(e){return this._refreshPromise?this._refreshPromise:(this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:s}=this.config,t=this.useCookieAuth,o=`${s}/cross-auth/social/refresh/simple`,n={};if(!t){const l=this.tokenStore.get()??"";l&&(n.access_token=l),e&&(n.refresh_token=e)}const i=await this.transport.request({url:o,method:"POST",headers:{"Content-Type":"application/json"},body:n,...t?{credentials:"include"}:{}});h.log("[CROSSx] silentRefresh 응답 — status:",i.status);const a=i.data;this.checkResponseError(a,"Silent refresh");const c=this.extractAccessToken(a);if(t&&!c){h.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!c)throw new m(_.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(c),!t){await this.storage.set(Qe,c);const l=this.extractRefreshToken(a);l&&await this.storage.set(Ne,l)}return h.log("[CROSSx] silentRefresh 성공"),c}async loadWallet(e,s){let t,o=!1;try{if(typeof this.walletProvider.checkWallet=="function"){h.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const n=await this.walletProvider.checkWallet();if(h.log("[CROSSx] 지갑 상태:",n),n==="migration_required")h.log("[CROSSx] migration_required → needsMigration = true"),o=!0;else if(n==="exists")try{const i=await this.walletProvider.getAddresses(e.id);i.length>0?(t=i[0].address,h.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):h.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(i){h.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",i)}}else h.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,h.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(n){if(n instanceof m&&n.code===_.MIGRATION_BACKUP_EXISTS)h.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),o=!0;else{if(n instanceof m&&(n.code===_.PROJECT_NOT_REGISTERED||n.code===_.PROJECT_ID_MISSING||n.code===_.ORIGIN_NOT_ALLOWED))throw h.error("[CROSSx] 프로젝트 설정 에러:",n.message),n;h.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",n)}}return h.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",o),{success:!0,address:t,user:e,needsMigration:o,tokenSignatureVerified:s}}}const Fs="crossx_access_token",Gs="crossx_refresh_token",Ws="crossx_user_info";class qs{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(Fs),await this.storage.remove(Gs)),await this.storage.remove(Ws)}}class Vs{constructor(e,s){this.storage=e,this.walletProvider=s}async execute(e,s){if(!this.walletProvider.migrateWallet)throw new m(_.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");h.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",s);const t=await this.walletProvider.migrateWallet(e,s);return h.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 o=new Uint8Array(s.length);for(let n=0;n<s.length;n++)o[n]=s[n]^t[n];s.fill(0),this.xorKey=t,this.encryptedBytes=o}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 o=await this.chainRegistry.getChain(t),n={jsonrpc:"2.0",method:e,params:s,id:Date.now()},a=(await this.transport.request({url:o.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:n})).data;if(a!=null&&a.error)throw new m(_.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class zs{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(o=>o(s))}removeAllListeners(){this.listeners.clear()}}const Fe={production:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function js(r){const e=r.environment;return e&&e in Fe?Fe[e]:null}function Ys(){try{if(typeof __CROSSX_CONFIG__<"u"){const r=typeof __CROSSX_CONFIG__=="string"?JSON.parse(__CROSSX_CONFIG__):__CROSSX_CONFIG__,e=js(r);if(e)return e}}catch{}return Fe.production}const Zs=2e3,It=6e4,Xs=1e3,Js=1e4,Qs="0x77359400",At="0x3B9ACA00",Tt=130,Ct=6,kt=18,er=0,tr=30*1e3,Q=class Q extends zs{constructor(e,s,t,o,n,i,a,c,l,d,u){super(),this.storage=t,this.crypto=o,this.transport=n,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._verifyPasswordMutex=null,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=s,e.logger&&St(e.logger),this.confirmation=l,this.passwordStore=u??new Qt,this.chainRegistry=d,this.jsonRpc=new Ks(d,n),this.signInUseCase=new Hs(this.internalConfig,t,o,i,n,a,c),this.signOutUseCase=new qs(this.internalConfig,t,c),this.migrateWalletUseCase=new Vs(t,a)}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.1.0 초기화 중..."),this.confirmation.setMessages(Et(this._config.locale));try{const s=Ys();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(o){if(!(o instanceof m&&o.code===_.PASSWORD_CANCELLED))throw o;h.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,this.emit("initialized",{restored:!!(t!=null&&t.success)}),t??null}catch(s){throw new m(_.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",s)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new m(_.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 m(_.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:n}=await this.createWallet(),i=await this.getAddresses(),a=await this.selectWalletIfMultiple(i);return{...s,address:(a==null?void 0:a.address)??n,needsMigration:!1,addresses:i}}const t=await this.getAddresses(),o=await this.selectWalletIfMultiple(t);return{...s,address:(o==null?void 0:o.address)??s.address,addresses:t}}catch(t){throw t instanceof m&&t.code===_.PASSWORD_CANCELLED&&(h.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(o=>h.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",o))),t}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new m(_.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 m&&s.code===_.PASSWORD_CANCELLED||h.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",s)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(_.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}),h.log("[CROSSx] migrateWallet 완료 — address:",s.address),s}catch(s){throw s instanceof m?s:new m(_.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",s)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new m(_.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.walletProvider.getAddresses(this.userId);return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new m(_.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.ensurePasswordForSigning();const o=s.length,i={address:(await this.walletProvider.getAddress(this.userId,o)).address,index:o};return s.push(i),i},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof m?e:new m(_.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(s){throw s instanceof m?s:new m(_.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(Et(e))}async createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new m(_.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");h.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(h.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const s=this.providerSub??this.userId;h.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",s);const t=await this.handleMigrationFlow(s);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new m(_.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}e==="exists"?await this.ensureVerifiedPassword():await this.ensurePasswordSetup();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}),h.log("[CROSSx] 지갑 준비 완료:",s.address),{address:s.address}}catch(s){if(s instanceof m&&s.code===_.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;h.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const o=await this.handleMigrationFlow(t);if(o)return this.address=o.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:o.address,index:0}),{address:o.address};throw new m(_.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw s}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return h.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(_.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=t==null?void 0:t.index,n=await this.walletProvider.getAddress(this.userId,o??0);let i;if(this.walletProvider.prepare&&(i=(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 m(_.USER_REJECTED,"사용자가 메시지 서명을 거부했습니다");try{const c=await this.withPasswordRetry(()=>this.walletProvider.signMessage(this.userId,e,s,t==null?void 0:t.index,i,n.address));return this.verifySignatureSigner(s,c.signature,n.address),{chainId:e,signature:c.signature,message:s,address:n.address}}catch(c){throw c instanceof m?c:new m(_.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,c)}}async signTypedData(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(_.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new m(_.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");await this.ensurePasswordForSigning(),Q.validateTypedDataChainId(e,s);const o=await this.walletProvider.getAddress(this.userId,(t==null?void 0:t.index)??0);let n;if(this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign-typed-data",{typedData:s,from:o.address})).uuid),!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:o.address,typedData:s,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(_.USER_REJECTED,"사용자가 타입 데이터 서명을 거부했습니다");try{const a=await this.withPasswordRetry(()=>this.walletProvider.signTypedData(this.userId,e,s,t==null?void 0:t.index,n,o.address));return Q.validateSignatureFormat(a.signature),{chainId:e,signature:a.signature,address:o.address}}catch(a){throw a instanceof m?a:new m(_.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,a)}}async signTypedDataOffchain(e,s){return this.signTypedData(Q.OFFCHAIN_CHAIN_ID,e,s)}async signTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(_.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=await this.withResolvedGasAndFee(s,e);let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("sign",{tx:o})).uuid);const i=Je(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:o.from,to:o.to,value:o.value,data:o.data,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(_.USER_REJECTED,"사용자가 트랜잭션 서명을 거부했습니다");try{const c=await this.withPasswordRetry(()=>this.walletProvider.signTransaction(this.userId,e,o,t==null?void 0:t.index,n));return Q.validateSignedTxFormat(c.signature),{chainId:e,signedTx:c.signature,txHash:c.txHash??""}}catch(c){if(c instanceof m)throw c;const l=c instanceof Error?c.message:String(c);throw new m(_.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${l}`,c)}}async sendTransaction(e,s,t){if(this.ensureAuthenticated(),!this.userId)throw new m(_.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");await this.ensurePasswordForSigning();const o=await this.withResolvedGasAndFee(s,e);let n;this.walletProvider.prepare&&(n=(await this.walletProvider.prepare("send",{tx:o})).uuid);const i=Je(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:o.from,to:o.to,value:o.value,data:o.data,gasLimit:o.gasLimit,gasPrice:o.gasPrice,maxFeePerGas:o.maxFeePerGas,maxPriorityFeePerGas:o.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:t==null?void 0:t.dappName,accountName:t==null?void 0:t.accountName}))throw new m(_.USER_REJECTED,"사용자가 트랜잭션을 거부했습니다");try{const c=await this.withPasswordRetry(async()=>{if(this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,o,n)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,o,t==null?void 0:t.index,n);return l.txHash??l.signature});return{chainId:e,txHash:c,status:"pending"}}catch(c){if(c instanceof m)throw c;const l=c instanceof Error?c.message:String(c);throw new m(_.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 o=t.intervalMs??Xs,n=Js,i=t.timeoutMs??It,a=Date.now()+i;let c=o;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,n)}throw new m(_.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,s,t={}){var b,y;const{intervalMs:o,timeoutMs:n,...i}=t,{txHash:a}=await this.sendTransaction(e,s,i),c=o??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??Zs,l=n??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??It,d=Je(e),u=s.from??"";let g,f;const p=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(E=>{g=E;const D=BigInt(E.gasUsed)*BigInt(E.effectiveGasPrice),U=s.value?BigInt(s.value):0n,M=Q.formatTxAmount(s.value,d.symbol,d.decimals),B=Q.formatTxAmount("0x"+D.toString(16),d.symbol,d.decimals),K=Q.formatTxAmount("0x"+(U+D).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:E.from,to:E.to??s.to,amount:M,fees:B,total:K,nativeSymbol:d.symbol,status:E.status==="0x1"?"success":"reverted"}}).catch(E=>(f=E instanceof Error?E:new Error(String(E)),{chainId:e,txHash:a,from:u,to:s.to,amount:Q.formatTxAmount(s.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:u,to:s.to},p),f)throw f;return{chainId:e,txHash:a,receipt:g}}setPassword(e){this.passwordStore.set(e)}clearPassword(){this.passwordStore.clear()}hasPassword(){return this.passwordStore.has()}async changePassword(e,s){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePassword!="function")throw new m(_.NOT_IMPLEMENTED,"changePassword가 구현되어 있지 않습니다");this.passwordStore.set(e);try{await t.changePassword(e,s),this.passwordStore.set(s),h.log("[CROSSx] 비밀번호 변경 완료")}catch(o){throw o instanceof m?o:new m(_.UNKNOWN_ERROR,"비밀번호 변경에 실패했습니다",o)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(_.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(o){const n=o instanceof Error?o.message:String(o);throw new m(_.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${s}): ${n}`,o)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const s=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(s==null?void 0:s.baseFeePerGas)??null}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(_.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(s){const t=s instanceof Error?s.message:String(s);throw new m(_.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,s)}}async getNonce(e){this.ensureAuthenticated();const s=this.address;if(!s)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[s,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof m)throw t;const o=t instanceof Error?t.message:String(t);throw new m(_.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${o}`,t)}}async getBalance(e){this.ensureAuthenticated();const s=this.address;if(!s)return{wei:"0x0",formatted:"0",chainId:e};try{const o=await this.jsonRpc.call("eth_getBalance",[s,"latest"],e)??"0x0";return{wei:o,formatted:Q.formatWei(o),chainId:e}}catch(t){if(t instanceof m)throw t;const o=t instanceof Error?t.message:String(t);throw new m(_.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${o}`,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),o=s/t,i=(s%t).toString().padStart(kt,"0").replace(/0+$/,"").slice(0,Ct);return i?`${o}.${i}`:`${o}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new Xt(this,e)}async walletRpc(e,s,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,s,t)}catch(o){if(o instanceof m)throw o;const n=o instanceof Error?o.message:String(o);throw new m(_.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${n}`,o)}}static formatTxAmount(e,s,t){if(!(!e||e==="0x"||e==="0x0"))try{const o=BigInt(e);if(o===0n)return;const n=10n**BigInt(t),i=o/n,c=(o%n).toString().padStart(t,"0").slice(0,Ct).replace(/0+$/,"");return`${c?`${i}.${c}`:`${i}`} ${s}`}catch{return}}async handleMigrationFlow(e){var a,c;h.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const s=await this.confirmation.showMigrationFoundPrompt();if(h.log("[CROSSx][Migration Phase 3] 사용자 선택:",s),s==="skip")return h.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let t,o=0,n=5,i=null;for(;;){o++,h.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${o}/${n})`,t?`— 이전 메시지: ${t}`:"");const l=await this.confirmation.showPinInputPrompt({errorMessage:t,attemptCount:o>1?o-1:void 0,maxAttempts:n});if(l===null)return h.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;h.log(`[CROSSx][Migration Phase 4] PIN 입력 완료 (${l.length}자리) — verify-pin API 호출`),t=void 0;try{const d=await((c=(a=this.walletProvider).verifyPin)==null?void 0:c.call(a,l,e));if(!d){h.log("[CROSSx][Migration Phase 4] verifyPin 미지원 — PIN 검증 생략"),i=l;break}if(d.valid){h.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),i=l;break}const u=d.pinStatus;if(n=u.maxAttempts,o=n-u.remainingAttempts,u.remainingAttempts===0&&u.lockExpiresAt){const g=u.lockExpiresAt*1e3,f=Math.max(1,Math.round((g-Date.now())/1e3)),p=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";h.warn(`[CROSSx][Migration Phase 4] verify-pin 잠금 — ${f}초, 메시지: ${p}`),await this.confirmation.showPinLockedPrompt(f,p),o=0,t="Your account lock has been lifted. You may try again."}else h.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${o}/${n})`),t="Incorrect PIN."}catch(d){if(!(d instanceof m))throw d;if(d.code===_.MIGRATION_PIN_LOCKED){const u=d.details;if(n=(u==null?void 0:u.maxAttempts)??5,(u==null?void 0:u.permanent)===!0)return h.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-pin)"),await this.confirmation.showPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const g=((u==null?void 0:u.lockExpiresAt)??0)*1e3,f=Math.max(1,Math.round((g-Date.now())/1e3)),p=f<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";h.warn(`[CROSSx][Migration Phase 4] verify-pin 이미 잠금 — ${f}초`),await this.confirmation.showPinLockedPrompt(f,p),o=0,t="Your account lock has been lifted. You may try again."}else throw h.error("[CROSSx][Migration Phase 4] verify-pin 실패 (복구 불가):",d),d}}h.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePasswordSetup();const l=await this.migrateWalletUseCase.execute(i,e);return h.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",l.address),l}catch(l){if(l instanceof m&&l.code===_.MIGRATION_FAILED)return h.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);throw h.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",l),l}}async withResolvedGasAndFee(e,s){const t=l=>!(l!=null&&l.trim()),o=e.nonce===void 0||e.nonce===null,n=t(e.gasLimit),i=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!o&&!n&&!i&&!a)return e;const c={...e};if(o){const l=c.from??this.address;if(l){h.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")");const d=await this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],s);c.nonce=parseInt(d??"0x0",16),h.log("[CROSSx] nonce 결과:",c.nonce)}}if(n&&(h.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),c.gasLimit=await this.estimateGas(e,s),h.log("[CROSSx] estimateGas 결과:",c.gasLimit)),i){h.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const l=await this.getBaseFeePerGas(s);if(l){const d=At;c.maxFeePerGas="0x"+(BigInt(l)+BigInt(d)).toString(16),c.maxPriorityFeePerGas=d,h.log("[CROSSx] Dynamic 체인 감지 — baseFee:",l,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Qs,h.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!i&&a&&(c.maxPriorityFeePerGas=At,h.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,s){const t=Q.extractDomainChainId(s);if(e==="0"){if(t!==void 0&&t!==0)throw new m(_.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const o=e.match(/^eip155:(\d+)$/);if(o){const n=Number(o[1]);if(t===void 0)throw new m(_.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==n)throw new m(_.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${n})와 일치하지 않습니다`)}}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 o=Number(t);return Number.isFinite(o)?o:void 0}static validateSignatureFormat(e){const s=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(s))throw new m(_.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(s.length!==Tt)throw new m(_.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 m(_.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(s.length<2)throw new m(_.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,s,t){if(this.crypto.recoverPersonalSignSigner)try{const o=this.crypto.recoverPersonalSignSigner(e,s);if(o.toLowerCase()!==t.toLowerCase())throw h.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:o}),new m(_.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${o}`);h.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(o){if(o instanceof m)throw o;h.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",o)}}applyAuthResult(e){var s,t,o,n;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=((o=e.user)==null?void 0:o.providerSub)??null,this.loginType=Q.normalizeLoginType((n=e.user)==null?void 0:n.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.passwordStore.clear(),this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePasswordSetup(){if(this.passwordStore.has())return;const e=await this.confirmation.showPasswordSetupPrompt();if(!e)throw new m(_.PASSWORD_CANCELLED,"사용자가 비밀번호 설정을 취소했습니다");this.passwordStore.set(e),h.log("[CROSSx] 비밀번호 설정 완료 (메모리 캐시)")}async ensurePasswordForSigning(e){if(this.passwordStore.has()&&!e)return;e&&this.passwordStore.clear();const s=await this.confirmation.showPasswordInputPrompt({errorMessage:e});if(!s)throw new m(_.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");this.passwordStore.set(s),h.log("[CROSSx] 비밀번호 입력 완료 (메모리 캐시)")}async ensureVerifiedPassword(e){if(e)this.passwordStore.clear();else if(this.passwordStore.has())return;if(this._verifyPasswordMutex&&!e){h.log("[CROSSx] ensureVerifiedPassword: 진행 중인 검증 대기"),await this._verifyPasswordMutex;return}let s,t;this._verifyPasswordMutex=new Promise((o,n)=>{s=o,t=n});try{if(typeof this.walletProvider.verifyPassword!="function"){const n=await this.confirmation.showPasswordInputPrompt({verifyMode:!0,errorMessage:e});if(!n)throw new m(_.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");this.passwordStore.set(n),h.log("[CROSSx] 비밀번호 캐시 완료 (verifyPassword 미지원, 로컬 전용)"),s();return}if(!await this.confirmation.showPasswordInputPrompt({verifyMode:!0,errorMessage:e,onSubmit:async n=>{this.passwordStore.set(n);try{return await this.walletProvider.verifyPassword(n)?(h.log("[CROSSx] 비밀번호 서버 검증 완료 (verify-password)"),{ok:!0}):(this.passwordStore.clear(),{ok:!1,error:"Incorrect password. Please try again."})}catch(i){if(this.passwordStore.clear(),i instanceof m&&i.code===_.PASSWORD_WRONG)return{ok:!1,error:"Incorrect password. Please try again."};throw i}}}))throw new m(_.PASSWORD_CANCELLED,"사용자가 비밀번호 입력을 취소했습니다");s()}catch(o){throw t(o),o}finally{this._verifyPasswordMutex=null}}async loadWalletAfterAuth(e){if(!this.userId)return;const s=await this.fetchWalletStatus();if(h.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",s),s!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const n=e!==void 0?t.find(i=>i.index===e)??t[0]:t[0];this.address=n.address,this.activeWalletIndex=n.index,h.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:n.address,index:n.index});return}h.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPassword();const o=await this.walletProvider.getAddress(this.userId,0);this.address=o.address,this.activeWalletIndex=0,h.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:o.address,index:0})}async withPasswordRetry(e){try{return await e()}catch(s){if(s instanceof m&&s.code===_.PASSWORD_WRONG)return h.warn("[CROSSx] 비밀번호 불일치 — 서버 검증 후 재시도"),await this.ensureVerifiedPassword("Incorrect password. Please enter your current password."),await e();throw s}}ensureInitialized(){if(!this.initialized)throw new m(_.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new m(_.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){this.clearAuthState(),this.tokenStore.clear(),this.passwordStore.clear(),this.initialized=!1,this.removeAllListeners(),St(null)}};Q.OFFCHAIN_CHAIN_ID="0";let Ge=Q;class sr{constructor(){this.prefix="crossx_"}async set(e,s){try{const t=JSON.stringify(s);localStorage.setItem(this.prefix+e,t)}catch(t){throw h.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 h.error("Storage get error:",s),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(s){throw h.error("Storage remove error:",s),s}}async clear(){try{Object.keys(localStorage).forEach(s=>{s.startsWith(this.prefix)&&localStorage.removeItem(s)})}catch(e){throw h.error("Storage clear error:",e),e}}}const rr="crossx-sdk",or=1,Se="data",De="keys",Rt="aes-primary",nr=12;class Pt{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(rr,or);t.onupgradeneeded=()=>{const o=t.result;o.objectStoreNames.contains(Se)||o.createObjectStore(Se),o.objectStoreNames.contains(De)||o.createObjectStore(De)},t.onsuccess=()=>e(t.result),t.onerror=()=>s(t.error)})}idbGet(e,s){return new Promise((t,o)=>{const i=this.db.transaction(e,"readonly").objectStore(e).get(s);i.onsuccess=()=>t(i.result),i.onerror=()=>o(i.error)})}idbPut(e,s,t){return new Promise((o,n)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,s);a.onsuccess=()=>o(),a.onerror=()=>n(a.error)})}idbDelete(e,s){return new Promise((t,o)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).delete(s);i.onsuccess=()=>t(),i.onerror=()=>o(i.error)})}idbClear(e){return new Promise((s,t)=>{const n=this.db.transaction(e,"readwrite").objectStore(e).clear();n.onsuccess=()=>s(),n.onerror=()=>t(n.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(De,Rt);if(e){this.cryptoKey=e;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(De,Rt,this.cryptoKey)}async encrypt(e){const s=new Uint8Array(nr);crypto.getRandomValues(s);const t=new TextEncoder().encode(e),o=await crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.cryptoKey,t);return{iv:s,ciphertext:o}}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),o=await this.encrypt(t);await this.idbPut(Se,e,o)}catch(t){throw h.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const s=await this.idbGet(Se,e);if(!s)return null;const t=await this.decrypt(s);return JSON.parse(t)}catch(s){return h.error("[CROSSx] IndexedDB get error:",s),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(Se,e)}catch(s){throw h.error("[CROSSx] IndexedDB remove error:",s),s}}async clear(){try{await this.ensureReady(),await this.idbClear(Se)}catch(e){throw h.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 dt(r){return r instanceof Uint8Array||ArrayBuffer.isView(r)&&r.constructor.name==="Uint8Array"}function pe(r,e=""){if(!Number.isSafeInteger(r)||r<0){const s=e&&`"${e}" `;throw new Error(`${s}expected integer >= 0, got ${r}`)}}function F(r,e,s=""){const t=dt(r),o=r==null?void 0:r.length,n=e!==void 0;if(!t||n&&o!==e){const i=s&&`"${s}" `,a=n?` of length ${e}`:"",c=t?`length=${o}`:`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");pe(r.outputLen),pe(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){F(r,void 0,"digestInto() output");const s=e.outputLen;if(r.length<s)throw new Error('"digestInto() output" expected to be of length >='+s)}function ir(r){return new Uint32Array(r.buffer,r.byteOffset,Math.floor(r.byteLength/4))}function Te(...r){for(let e=0;e<r.length;e++)r[e].fill(0)}function et(r){return new DataView(r.buffer,r.byteOffset,r.byteLength)}function ae(r,e){return r<<32-e|r>>>e}const ar=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function cr(r){return r<<24&4278190080|r<<8&16711680|r>>>8&65280|r>>>24&255}function lr(r){for(let e=0;e<r.length;e++)r[e]=cr(r[e]);return r}const Ot=ar?r=>r:lr,ss=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",dr=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function Oe(r){if(F(r),ss)return r.toHex();let e="";for(let s=0;s<r.length;s++)e+=dr[r[s]];return e}const de={_0:48,_9:57,A:65,F:70,a:97,f:102};function Nt(r){if(r>=de._0&&r<=de._9)return r-de._0;if(r>=de.A&&r<=de.F)return r-(de.A-10);if(r>=de.a&&r<=de.f)return r-(de.a-10)}function We(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 o=0,n=0;o<s;o++,n+=2){const i=Nt(r.charCodeAt(n)),a=Nt(r.charCodeAt(n+1));if(i===void 0||a===void 0){const c=r[n]+r[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}t[o]=i*16+a}return t}function we(...r){let e=0;for(let t=0;t<r.length;t++){const o=r[t];F(o),e+=o.length}const s=new Uint8Array(e);for(let t=0,o=0;t<r.length;t++){const n=r[t];s.set(n,o),o+=n.length}return s}function rs(r,e={}){const s=(o,n)=>r(n).update(o).digest(),t=r(void 0);return s.outputLen=t.outputLen,s.blockLen=t.blockLen,s.create=o=>r(o),Object.assign(s,e),Object.freeze(s)}function os(r=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(r))}const ur=r=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,r])});function hr(r,e,s){return r&e^~r&s}function pr(r,e,s){return r&e^r&s^e&s}class fr{constructor(e,s,t,o){S(this,"blockLen");S(this,"outputLen");S(this,"padOffset");S(this,"isLE");S(this,"buffer");S(this,"view");S(this,"finished",!1);S(this,"length",0);S(this,"pos",0);S(this,"destroyed",!1);this.blockLen=e,this.outputLen=s,this.padOffset=t,this.isLE=o,this.buffer=new Uint8Array(e),this.view=et(this.buffer)}update(e){Ae(this),F(e);const{view:s,buffer:t,blockLen:o}=this,n=e.length;for(let i=0;i<n;){const a=Math.min(o-this.pos,n-i);if(a===o){const c=et(e);for(;o<=n-i;i+=o)this.process(c,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===o&&(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:o,isLE:n}=this;let{pos:i}=this;s[i++]=128,Te(this.buffer.subarray(i)),this.padOffset>o-i&&(this.process(t,0),i=0);for(let u=i;u<o;u++)s[u]=0;t.setBigUint64(o-8,BigInt(this.length*8),n),this.process(t,0);const a=et(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let u=0;u<l;u++)a.setUint32(4*u,d[u],n)}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:o,finished:n,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=n,e.length=o,e.pos=a,o%s&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const _e=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Me=BigInt(2**32-1),Lt=BigInt(32);function _r(r,e=!1){return e?{h:Number(r&Me),l:Number(r>>Lt&Me)}:{h:Number(r>>Lt&Me)|0,l:Number(r&Me)|0}}function gr(r,e=!1){const s=r.length;let t=new Uint32Array(s),o=new Uint32Array(s);for(let n=0;n<s;n++){const{h:i,l:a}=_r(r[n],e);[t[n],o[n]]=[i,a]}return[t,o]}const xr=(r,e,s)=>r<<s|e>>>32-s,wr=(r,e,s)=>e<<s|r>>>32-s,mr=(r,e,s)=>e<<s-32|r>>>64-s,yr=(r,e,s)=>r<<s-32|e>>>64-s,br=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),ge=new Uint32Array(64);class vr extends fr{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:s,C:t,D:o,E:n,F:i,G:a,H:c}=this;return[e,s,t,o,n,i,a,c]}set(e,s,t,o,n,i,a,c){this.A=e|0,this.B=s|0,this.C=t|0,this.D=o|0,this.E=n|0,this.F=i|0,this.G=a|0,this.H=c|0}process(e,s){for(let u=0;u<16;u++,s+=4)ge[u]=e.getUint32(s,!1);for(let u=16;u<64;u++){const g=ge[u-15],f=ge[u-2],p=ae(g,7)^ae(g,18)^g>>>3,b=ae(f,17)^ae(f,19)^f>>>10;ge[u]=b+ge[u-7]+p+ge[u-16]|0}let{A:t,B:o,C:n,D:i,E:a,F:c,G:l,H:d}=this;for(let u=0;u<64;u++){const g=ae(a,6)^ae(a,11)^ae(a,25),f=d+g+hr(a,c,l)+br[u]+ge[u]|0,b=(ae(t,2)^ae(t,13)^ae(t,22))+pr(t,o,n)|0;d=l,l=c,c=a,a=i+f|0,i=n,n=o,o=t,t=f+b|0}t=t+this.A|0,o=o+this.B|0,n=n+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,o,n,i,a,c,l,d)}roundClean(){Te(ge)}destroy(){this.set(0,0,0,0,0,0,0,0),Te(this.buffer)}}class Sr extends vr{constructor(){super(32);S(this,"A",_e[0]|0);S(this,"B",_e[1]|0);S(this,"C",_e[2]|0);S(this,"D",_e[3]|0);S(this,"E",_e[4]|0);S(this,"F",_e[5]|0);S(this,"G",_e[6]|0);S(this,"H",_e[7]|0)}}const Er=rs(()=>new Sr,ur(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ut=BigInt(0),it=BigInt(1);function qe(r,e=""){if(typeof r!="boolean"){const s=e&&`"${e}" `;throw new Error(s+"expected boolean, got type="+typeof r)}return r}function ns(r){if(typeof r=="bigint"){if(!He(r))throw new Error("positive bigint expected, got "+r)}else pe(r);return r}function $e(r){const e=ns(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===""?ut:BigInt("0x"+r)}function Ye(r){return is(Oe(r))}function as(r){return is(Oe(Ir(F(r)).reverse()))}function ht(r,e){pe(e),r=ns(r);const s=We(r.toString(16).padStart(e*2,"0"));if(s.length!==e)throw new Error("number too large");return s}function cs(r,e){return ht(r,e).reverse()}function Ir(r){return Uint8Array.from(r)}const He=r=>typeof r=="bigint"&&ut<=r;function Ar(r,e,s){return He(r)&&He(e)&&He(s)&&e<=r&&r<s}function Tr(r,e,s,t){if(!Ar(e,s,t))throw new Error("expected valid "+r+": "+s+" <= n < "+t+", got "+e)}function Cr(r){let e;for(e=0;r>ut;r>>=it,e+=1);return e}const pt=r=>(it<<BigInt(r))-it;function kr(r,e,s){if(pe(r,"hashLen"),pe(e,"qByteLen"),typeof s!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),o=Uint8Array.of(),n=Uint8Array.of(0),i=Uint8Array.of(1),a=1e3;let c=t(r),l=t(r),d=0;const u=()=>{c.fill(1),l.fill(0),d=0},g=(...y)=>s(l,we(c,...y)),f=(y=o)=>{l=g(n,y),c=g(),y.length!==0&&(l=g(i,y),c=g())},p=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const E=[];for(;y<e;){c=g();const D=c.slice();E.push(D),y+=c.length}return we(...E)};return(y,E)=>{u(),f(y);let D;for(;!(D=E(p()));)f();return u(),D}}function ft(r,e={},s={}){if(!r||typeof r!="object")throw new Error("expected valid options object");function t(n,i,a){const c=r[n];if(a&&c===void 0)return;const l=typeof c;if(l!==i||c===null)throw new Error(`param "${n}" is invalid: expected ${i}, got ${l}`)}const o=(n,i)=>Object.entries(n).forEach(([a,c])=>t(a,c,i));o(e,!1),o(s,!0)}function Dt(r){const e=new WeakMap;return(s,...t)=>{const o=e.get(s);if(o!==void 0)return o;const n=r(s,...t);return e.set(s,n),n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ee=BigInt(0),Z=BigInt(1),be=BigInt(2),ls=BigInt(3),ds=BigInt(4),us=BigInt(5),Rr=BigInt(7),hs=BigInt(8),Pr=BigInt(9),ps=BigInt(16);function ne(r,e){const s=r%e;return s>=ee?s:e+s}function oe(r,e,s){let t=r;for(;e-- >ee;)t*=t,t%=s;return t}function Mt(r,e){if(r===ee)throw new Error("invert: expected non-zero number");if(e<=ee)throw new Error("invert: expected positive modulus, got "+e);let s=ne(r,e),t=e,o=ee,n=Z;for(;s!==ee;){const a=t/s,c=t%s,l=o-n*a;t=s,s=c,o=n,n=l}if(t!==Z)throw new Error("invert: does not exist");return ne(o,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+Z)/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,be),o=r.pow(t,s),n=r.mul(e,o),i=r.mul(r.mul(n,be),o),a=r.mul(n,r.sub(i,r.ONE));return _t(r,a,e),a}function Nr(r){const e=Ze(r),s=_s(r),t=s(e,e.neg(e.ONE)),o=s(e,t),n=s(e,e.neg(t)),i=(r+Rr)/ps;return(a,c)=>{let l=a.pow(c,i),d=a.mul(l,t);const u=a.mul(l,o),g=a.mul(l,n),f=a.eql(a.sqr(d),c),p=a.eql(a.sqr(u),c);l=a.cmov(l,d,f),d=a.cmov(g,u,p);const b=a.eql(a.sqr(d),c),y=a.cmov(l,d,b);return _t(a,y,c),y}}function _s(r){if(r<ls)throw new Error("sqrt is not defined for small field");let e=r-Z,s=0;for(;e%be===ee;)e/=be,s++;let t=be;const o=Ze(r);for(;$t(o,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(s===1)return fs;let n=o.pow(t,e);const i=(e+Z)/be;return function(c,l){if(c.is0(l))return l;if($t(c,l)!==1)throw new Error("Cannot find square root");let d=s,u=c.mul(c.ONE,n),g=c.pow(l,e),f=c.pow(l,i);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let p=1,b=c.sqr(g);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===d)throw new Error("Cannot find square root");const y=Z<<BigInt(d-p-1),E=c.pow(u,y);d=p,u=c.sqr(E),g=c.mul(g,u),f=c.mul(f,E)}return f}}function Lr(r){return r%ds===ls?fs:r%hs===us?Or:r%ps===Pr?Nr(r):_s(r)}const Dr=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Mr(r){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},s=Dr.reduce((t,o)=>(t[o]="function",t),e);return ft(r,s),r}function $r(r,e,s){if(s<ee)throw new Error("invalid exponent, negatives unsupported");if(s===ee)return r.ONE;if(s===Z)return e;let t=r.ONE,o=e;for(;s>ee;)s&Z&&(t=r.mul(t,o)),o=r.sqr(o),s>>=Z;return t}function gs(r,e,s=!1){const t=new Array(e.length).fill(s?r.ZERO:void 0),o=e.reduce((i,a,c)=>r.is0(a)?i:(t[c]=i,r.mul(i,a)),r.ONE),n=r.inv(o);return e.reduceRight((i,a,c)=>r.is0(a)?i:(t[c]=r.mul(i,t[c]),r.mul(i,a)),n),t}function $t(r,e){const s=(r.ORDER-Z)/be,t=r.pow(e,s),o=r.eql(t,r.ONE),n=r.eql(t,r.ZERO),i=r.eql(t,r.neg(r.ONE));if(!o&&!n&&!i)throw new Error("invalid Legendre symbol result");return o?1:n?0:-1}function Br(r,e){e!==void 0&&pe(e);const s=e!==void 0?e:r.toString(2).length,t=Math.ceil(s/8);return{nBitLength:s,nByteLength:t}}class Ur{constructor(e,s={}){S(this,"ORDER");S(this,"BITS");S(this,"BYTES");S(this,"isLE");S(this,"ZERO",ee);S(this,"ONE",Z);S(this,"_lengths");S(this,"_sqrt");S(this,"_mod");var i;if(e<=ee)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:o,nByteLength:n}=Br(e,t);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=o,this.BYTES=n,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return ne(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ee<=e&&e<this.ORDER}is0(e){return e===ee}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&Z)===Z}neg(e){return ne(-e,this.ORDER)}eql(e,s){return e===s}sqr(e){return ne(e*e,this.ORDER)}add(e,s){return ne(e+s,this.ORDER)}sub(e,s){return ne(e-s,this.ORDER)}mul(e,s){return ne(e*s,this.ORDER)}pow(e,s){return $r(this,e,s)}div(e,s){return ne(e*Mt(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 Mt(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=Lr(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?cs(e,this.BYTES):ht(e,this.BYTES)}fromBytes(e,s=!1){F(e);const{_lengths:t,BYTES:o,isLE:n,ORDER:i,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>o)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(o);l.set(e,n?0:l.length-e.length),e=l}if(e.length!==o)throw new Error("Field.fromBytes: expected "+o+" bytes, got "+e.length);let c=n?as(e):Ye(e);if(a&&(c=ne(c,i)),!s&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return gs(this,e)}cmov(e,s,t){return t?s:e}}function Ze(r,e={}){return new Ur(r,e)}function xs(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 ws(r){const e=xs(r);return e+Math.ceil(e/2)}function Hr(r,e,s=!1){F(r);const t=r.length,o=xs(e),n=ws(e);if(t<16||t<n||t>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+t);const i=s?as(r):Ye(r),a=ne(i,e-Z)+Z;return s?cs(a,o):ht(a,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ce=BigInt(0),ve=BigInt(1);function Ve(r,e){const s=e.negate();return r?s:e}function Bt(r,e){const s=gs(r.Fp,e.map(t=>t.Z));return e.map((t,o)=>r.fromAffine(t.toAffine(s[o])))}function ms(r,e){if(!Number.isSafeInteger(r)||r<=0||r>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+r)}function tt(r,e){ms(r,e);const s=Math.ceil(e/r)+1,t=2**(r-1),o=2**r,n=pt(r),i=BigInt(r);return{windows:s,windowSize:t,mask:n,maxNumber:o,shiftBy:i}}function Ut(r,e,s){const{windowSize:t,mask:o,maxNumber:n,shiftBy:i}=s;let a=Number(r&o),c=r>>i;a>t&&(a-=n,c+=ve);const l=e*t,d=l+Math.abs(a)-1,u=a===0,g=a<0,f=e%2!==0;return{nextN:c,offset:d,isZero:u,isNeg:g,isNegF:f,offsetF:l}}const st=new WeakMap,ys=new WeakMap;function rt(r){return ys.get(r)||1}function Ht(r){if(r!==Ce)throw new Error("invalid wNAF")}class Fr{constructor(e,s){S(this,"BASE");S(this,"ZERO");S(this,"Fn");S(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=s}_unsafeLadder(e,s,t=this.ZERO){let o=e;for(;s>Ce;)s&ve&&(t=t.add(o)),o=o.double(),s>>=ve;return t}precomputeWindow(e,s){const{windows:t,windowSize:o}=tt(s,this.bits),n=[];let i=e,a=i;for(let c=0;c<t;c++){a=i,n.push(a);for(let l=1;l<o;l++)a=a.add(i),n.push(a);i=a.double()}return n}wNAF(e,s,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let o=this.ZERO,n=this.BASE;const i=tt(e,this.bits);for(let a=0;a<i.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:u,isNegF:g,offsetF:f}=Ut(t,a,i);t=c,d?n=n.add(Ve(g,s[f])):o=o.add(Ve(u,s[l]))}return Ht(t),{p:o,f:n}}wNAFUnsafe(e,s,t,o=this.ZERO){const n=tt(e,this.bits);for(let i=0;i<n.windows&&t!==Ce;i++){const{nextN:a,offset:c,isZero:l,isNeg:d}=Ut(t,i,n);if(t=a,!l){const u=s[c];o=o.add(d?u.negate():u)}}return Ht(t),o}getPrecomputes(e,s,t){let o=st.get(s);return o||(o=this.precomputeWindow(s,e),e!==1&&(typeof t=="function"&&(o=t(o)),st.set(s,o))),o}cached(e,s,t){const o=rt(e);return this.wNAF(o,this.getPrecomputes(o,e,t),s)}unsafe(e,s,t,o){const n=rt(e);return n===1?this._unsafeLadder(e,s,o):this.wNAFUnsafe(n,this.getPrecomputes(n,e,t),s,o)}createCache(e,s){ms(s,this.bits),ys.set(e,s),st.delete(e)}hasCache(e){return rt(e)!==1}}function Gr(r,e,s,t){let o=e,n=r.ZERO,i=r.ZERO;for(;s>Ce||t>Ce;)s&ve&&(n=n.add(o)),t&ve&&(i=i.add(o)),o=o.double(),s>>=ve,t>>=ve;return{p1:n,p2:i}}function Ft(r,e,s){if(e){if(e.ORDER!==r)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Mr(e),e}else return Ze(r,{isLE:s})}function Wr(r,e,s={},t){if(t===void 0&&(t=r==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${r} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>Ce))throw new Error(`CURVE.${c} must be positive bigint`)}const o=Ft(e.p,s.Fp,t),n=Ft(e.n,s.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!o.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:o,Fn:n}}function qr(r,e){return function(t){const o=r(t);return{secretKey:o,publicKey:e(o)}}}class bs{constructor(e,s){S(this,"oHash");S(this,"iHash");S(this,"blockLen");S(this,"outputLen");S(this,"finished",!1);S(this,"destroyed",!1);if(es(e),F(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,o=new Uint8Array(t);o.set(s.length>t?e.create().update(s).digest():s);for(let n=0;n<o.length;n++)o[n]^=54;this.iHash.update(o),this.oHash=e.create();for(let n=0;n<o.length;n++)o[n]^=106;this.oHash.update(o),Te(o)}update(e){return Ae(this),this.iHash.update(e),this}digestInto(e){Ae(this),F(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:o,destroyed:n,blockLen:i,outputLen:a}=this;return e=e,e.finished=o,e.destroyed=n,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 Gt=(r,e)=>(r+(r>=0?e:-e)/Ss)/e;function Vr(r,e,s){const[[t,o],[n,i]]=e,a=Gt(i*r,s),c=Gt(-o*r,s);let l=r-a*t-c*n,d=-a*o-c*i;const u=l<ue,g=d<ue;u&&(l=-l),g&&(d=-d);const f=pt(Math.ceil(Cr(s)/2))+Ie;if(l<ue||l>=f||d<ue||d>=f)throw new Error("splitScalar (endomorphism): failed, k="+r);return{k1neg:u,k1:l,k2neg:g,k2:d}}function at(r){if(!["compact","recovered","der"].includes(r))throw new Error('Signature format must be "compact", "recovered", or "der"');return r}function ot(r,e){const s={};for(let t of Object.keys(e))s[t]=r[t]===void 0?e[t]:r[t];return qe(s.lowS,"lowS"),qe(s.prehash,"prehash"),s.format!==void 0&&at(s.format),s}class Kr extends Error{constructor(e=""){super(e)}}const xe={Err:Kr,_tlv:{encode:(r,e)=>{const{Err:s}=xe;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,o=$e(t);if(o.length/2&128)throw new s("tlv.encode: long form length too big");const n=t>127?$e(o.length/2|128):"";return $e(r)+n+o+e},decode(r,e){const{Err:s}=xe;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 o=e[t++],n=!!(o&128);let i=0;if(!n)i=o;else{const c=o&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}=xe;if(r<ue)throw new e("integer: negative integers are not allowed");let s=$e(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}=xe;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}=xe,o=F(r,void 0,"signature"),{v:n,l:i}=t.decode(48,o);if(i.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,n),{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}=xe,t=e.encode(2,s.encode(r.r)),o=e.encode(2,s.encode(r.s)),n=t+o;return e.encode(48,n)}},ue=BigInt(0),Ie=BigInt(1),Ss=BigInt(2),Be=BigInt(3),zr=BigInt(4);function jr(r,e={}){const s=Wr("weierstrass",r,e),{Fp:t,Fn:o}=s;let n=s.CURVE;const{h:i,n:a}=n;ft(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(n.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=Is(t,o);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function u(L,x,w){const{x:v,y:A}=x.toAffine(),k=t.toBytes(v);if(qe(w,"isCompressed"),w){d();const C=!t.isOdd(A);return we(Es(C),k)}else return we(Uint8Array.of(4),k,t.toBytes(A))}function g(L){F(L,void 0,"Point");const{publicKey:x,publicKeyUncompressed:w}=l,v=L.length,A=L[0],k=L.subarray(1);if(v===x&&(A===2||A===3)){const C=t.fromBytes(k);if(!t.isValid(C))throw new Error("bad point: is not on curve, wrong x");const R=b(C);let I;try{I=t.sqrt(R)}catch(q){const H=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}d();const P=t.isOdd(I);return(A&1)===1!==P&&(I=t.neg(I)),{x:C,y:I}}else if(v===w&&A===4){const C=t.BYTES,R=t.fromBytes(k.subarray(0,C)),I=t.fromBytes(k.subarray(C,C*2));if(!y(R,I))throw new Error("bad point: is not on curve");return{x:R,y:I}}else throw new Error(`bad point: got length ${v}, expected compressed=${x} or uncompressed=${w}`)}const f=e.toBytes||u,p=e.fromBytes||g;function b(L){const x=t.sqr(L),w=t.mul(x,L);return t.add(t.add(w,t.mul(L,n.a)),n.b)}function y(L,x){const w=t.sqr(x),v=b(L);return t.eql(w,v)}if(!y(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const E=t.mul(t.pow(n.a,Be),zr),D=t.mul(t.sqr(n.b),BigInt(27));if(t.is0(t.add(E,D)))throw new Error("bad curve params: a or b");function U(L,x,w=!1){if(!t.isValid(x)||w&&t.is0(x))throw new Error(`bad point coordinate ${L}`);return x}function M(L){if(!(L instanceof J))throw new Error("Weierstrass Point expected")}function B(L){if(!c||!c.basises)throw new Error("no endo");return Vr(L,c.basises,o.ORDER)}const K=Dt((L,x)=>{const{X:w,Y:v,Z:A}=L;if(t.eql(A,t.ONE))return{x:w,y:v};const k=L.is0();x==null&&(x=k?t.ONE:t.inv(A));const C=t.mul(w,x),R=t.mul(v,x),I=t.mul(A,x);if(k)return{x:t.ZERO,y:t.ZERO};if(!t.eql(I,t.ONE))throw new Error("invZ was invalid");return{x:C,y:R}}),le=Dt(L=>{if(L.is0()){if(e.allowInfinityPoint&&!t.is0(L.Y))return;throw new Error("bad point: ZERO")}const{x,y:w}=L.toAffine();if(!t.isValid(x)||!t.isValid(w))throw new Error("bad point: x or y not field elements");if(!y(x,w))throw new Error("bad point: equation left != right");if(!L.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function fe(L,x,w,v,A){return w=new J(t.mul(w.X,L),w.Y,w.Z),x=Ve(v,x),w=Ve(A,w),x.add(w)}const $=class ${constructor(x,w,v){S(this,"X");S(this,"Y");S(this,"Z");this.X=U("x",x),this.Y=U("y",w,!0),this.Z=U("z",v),Object.freeze(this)}static CURVE(){return n}static fromAffine(x){const{x:w,y:v}=x||{};if(!x||!t.isValid(w)||!t.isValid(v))throw new Error("invalid affine point");if(x instanceof $)throw new Error("projective point not allowed");return t.is0(w)&&t.is0(v)?$.ZERO:new $(w,v,t.ONE)}static fromBytes(x){const w=$.fromAffine(p(F(x,void 0,"point")));return w.assertValidity(),w}static fromHex(x){return $.fromBytes(We(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,w=!0){return ie.createCache(this,x),w||this.multiply(Be),this}assertValidity(){le(this)}hasEvenY(){const{y:x}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(x)}equals(x){M(x);const{X:w,Y:v,Z:A}=this,{X:k,Y:C,Z:R}=x,I=t.eql(t.mul(w,R),t.mul(k,A)),P=t.eql(t.mul(v,R),t.mul(C,A));return I&&P}negate(){return new $(this.X,t.neg(this.Y),this.Z)}double(){const{a:x,b:w}=n,v=t.mul(w,Be),{X:A,Y:k,Z:C}=this;let R=t.ZERO,I=t.ZERO,P=t.ZERO,N=t.mul(A,A),q=t.mul(k,k),H=t.mul(C,C),O=t.mul(A,k);return O=t.add(O,O),P=t.mul(A,C),P=t.add(P,P),R=t.mul(x,P),I=t.mul(v,H),I=t.add(R,I),R=t.sub(q,I),I=t.add(q,I),I=t.mul(R,I),R=t.mul(O,R),P=t.mul(v,P),H=t.mul(x,H),O=t.sub(N,H),O=t.mul(x,O),O=t.add(O,P),P=t.add(N,N),N=t.add(P,N),N=t.add(N,H),N=t.mul(N,O),I=t.add(I,N),H=t.mul(k,C),H=t.add(H,H),N=t.mul(H,O),R=t.sub(R,N),P=t.mul(H,q),P=t.add(P,P),P=t.add(P,P),new $(R,I,P)}add(x){M(x);const{X:w,Y:v,Z:A}=this,{X:k,Y:C,Z:R}=x;let I=t.ZERO,P=t.ZERO,N=t.ZERO;const q=n.a,H=t.mul(n.b,Be);let O=t.mul(w,k),V=t.mul(v,C),j=t.mul(A,R),se=t.add(w,v),G=t.add(k,C);se=t.mul(se,G),G=t.add(O,V),se=t.sub(se,G),G=t.add(w,A);let Y=t.add(k,R);return G=t.mul(G,Y),Y=t.add(O,j),G=t.sub(G,Y),Y=t.add(v,A),I=t.add(C,R),Y=t.mul(Y,I),I=t.add(V,j),Y=t.sub(Y,I),N=t.mul(q,G),I=t.mul(H,j),N=t.add(I,N),I=t.sub(V,N),N=t.add(V,N),P=t.mul(I,N),V=t.add(O,O),V=t.add(V,O),j=t.mul(q,j),G=t.mul(H,G),V=t.add(V,j),j=t.sub(O,j),j=t.mul(q,j),G=t.add(G,j),O=t.mul(V,G),P=t.add(P,O),O=t.mul(Y,G),I=t.mul(se,I),I=t.sub(I,O),O=t.mul(se,V),N=t.mul(Y,N),N=t.add(N,O),new $(I,P,N)}subtract(x){return this.add(x.negate())}is0(){return this.equals($.ZERO)}multiply(x){const{endo:w}=e;if(!o.isValidNot0(x))throw new Error("invalid scalar: out of range");let v,A;const k=C=>ie.cached(this,C,R=>Bt($,R));if(w){const{k1neg:C,k1:R,k2neg:I,k2:P}=B(x),{p:N,f:q}=k(R),{p:H,f:O}=k(P);A=q.add(O),v=fe(w.beta,N,H,C,I)}else{const{p:C,f:R}=k(x);v=C,A=R}return Bt($,[v,A])[0]}multiplyUnsafe(x){const{endo:w}=e,v=this;if(!o.isValid(x))throw new Error("invalid scalar: out of range");if(x===ue||v.is0())return $.ZERO;if(x===Ie)return v;if(ie.hasCache(this))return this.multiply(x);if(w){const{k1neg:A,k1:k,k2neg:C,k2:R}=B(x),{p1:I,p2:P}=Gr($,v,k,R);return fe(w.beta,I,P,A,C)}else return ie.unsafe(v,x)}toAffine(x){return K(this,x)}isTorsionFree(){const{isTorsionFree:x}=e;return i===Ie?!0:x?x($,this):ie.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=e;return i===Ie?this:x?x($,this):this.multiplyUnsafe(i)}isSmallOrder(){return this.multiplyUnsafe(i).is0()}toBytes(x=!0){return qe(x,"isCompressed"),this.assertValidity(),f($,this,x)}toHex(x=!0){return Oe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};S($,"BASE",new $(n.Gx,n.Gy,t.ONE)),S($,"ZERO",new $(t.ZERO,t.ONE,t.ZERO)),S($,"Fp",t),S($,"Fn",o);let J=$;const me=o.BITS,ie=new Fr(J,e.endo?Math.ceil(me/2):me);return J.BASE.precompute(8),J}function Es(r){return Uint8Array.of(r?2:3)}function Is(r,e){return{secretKey:e.BYTES,publicKey:1+r.BYTES,publicKeyUncompressed:1+2*r.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Yr(r,e={}){const{Fn:s}=r,t=e.randomBytes||os,o=Object.assign(Is(r.Fp,s),{seed:ws(s.ORDER)});function n(f){try{const p=s.fromBytes(f);return s.isValidNot0(p)}catch{return!1}}function i(f,p){const{publicKey:b,publicKeyUncompressed:y}=o;try{const E=f.length;return p===!0&&E!==b||p===!1&&E!==y?!1:!!r.fromBytes(f)}catch{return!1}}function a(f=t(o.seed)){return Hr(F(f,o.seed,"seed"),s.ORDER)}function c(f,p=!0){return r.BASE.multiply(s.fromBytes(f)).toBytes(p)}function l(f){const{secretKey:p,publicKey:b,publicKeyUncompressed:y}=o;if(!dt(f)||"_lengths"in s&&s._lengths||p===b)return;const E=F(f,void 0,"key").length;return E===b||E===y}function d(f,p,b=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const y=s.fromBytes(f);return r.fromBytes(p).multiply(y).toBytes(b)}const u={isValidSecretKey:n,isValidPublicKey:i,randomSecretKey:a},g=qr(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:g,Point:r,utils:u,lengths:o})}function Zr(r,e,s={}){es(e),ft(s,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),s=Object.assign({},s);const t=s.randomBytes||os,o=s.hmac||((x,w)=>vs(e,x,w)),{Fp:n,Fn:i}=r,{ORDER:a,BITS:c}=i,{keygen:l,getPublicKey:d,getSharedSecret:u,utils:g,lengths:f}=Yr(r,s),p={prehash:!0,lowS:typeof s.lowS=="boolean"?s.lowS:!0,format:"compact",extraEntropy:!1},b=a*Ss<n.ORDER;function y(x){const w=a>>Ie;return x>w}function E(x,w){if(!i.isValidNot0(w))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return w}function D(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function U(x,w){at(w);const v=f.signature,A=w==="compact"?v:w==="recovered"?v+1:void 0;return F(x,A)}class M{constructor(w,v,A){S(this,"r");S(this,"s");S(this,"recovery");if(this.r=E("r",w),this.s=E("s",v),A!=null){if(D(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(w,v=p.format){U(w,v);let A;if(v==="der"){const{r:I,s:P}=xe.toSig(F(w));return new M(I,P)}v==="recovered"&&(A=w[0],v="compact",w=w.subarray(1));const k=f.signature/2,C=w.subarray(0,k),R=w.subarray(k,k*2);return new M(i.fromBytes(C),i.fromBytes(R),A)}static fromHex(w,v){return this.fromBytes(We(w),v)}assertRecovery(){const{recovery:w}=this;if(w==null)throw new Error("invalid recovery id: must be present");return w}addRecoveryBit(w){return new M(this.r,this.s,w)}recoverPublicKey(w){const{r:v,s:A}=this,k=this.assertRecovery(),C=k===2||k===3?v+a:v;if(!n.isValid(C))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const R=n.toBytes(C),I=r.fromBytes(we(Es((k&1)===0),R)),P=i.inv(C),N=K(F(w,void 0,"msgHash")),q=i.create(-N*P),H=i.create(A*P),O=r.BASE.multiplyUnsafe(q).add(I.multiplyUnsafe(H));if(O.is0())throw new Error("invalid recovery: point at infinify");return O.assertValidity(),O}hasHighS(){return y(this.s)}toBytes(w=p.format){if(at(w),w==="der")return We(xe.hexFromSig(this));const{r:v,s:A}=this,k=i.toBytes(v),C=i.toBytes(A);return w==="recovered"?(D(),we(Uint8Array.of(this.assertRecovery()),k,C)):we(k,C)}toHex(w){return Oe(this.toBytes(w))}}const B=s.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const v=Ye(w),A=w.length*8-c;return A>0?v>>BigInt(A):v},K=s.bits2int_modN||function(w){return i.create(B(w))},le=pt(c);function fe(x){return Tr("num < 2^"+c,x,ue,le),i.toBytes(x)}function J(x,w){return F(x,void 0,"message"),w?F(e(x),void 0,"prehashed message"):x}function me(x,w,v){const{lowS:A,prehash:k,extraEntropy:C}=ot(v,p);x=J(x,k);const R=K(x),I=i.fromBytes(w);if(!i.isValidNot0(I))throw new Error("invalid private key");const P=[fe(I),fe(R)];if(C!=null&&C!==!1){const O=C===!0?t(f.secretKey):C;P.push(F(O,void 0,"extraEntropy"))}const N=we(...P),q=R;function H(O){const V=B(O);if(!i.isValidNot0(V))return;const j=i.inv(V),se=r.BASE.multiply(V).toAffine(),G=i.create(se.x);if(G===ue)return;const Y=i.create(j*i.create(q+G*I));if(Y===ue)return;let bt=(se.x===G?0:2)|Number(se.y&Ie),vt=Y;return A&&y(Y)&&(vt=i.neg(Y),bt^=1),new M(G,vt,b?void 0:bt)}return{seed:N,k2sig:H}}function ie(x,w,v={}){const{seed:A,k2sig:k}=me(x,w,v);return kr(e.outputLen,i.BYTES,o)(A,k).toBytes(v.format)}function $(x,w,v,A={}){const{lowS:k,prehash:C,format:R}=ot(A,p);if(v=F(v,void 0,"publicKey"),w=J(w,C),!dt(x)){const I=x instanceof M?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+I)}U(x,R);try{const I=M.fromBytes(x,R),P=r.fromBytes(v);if(k&&I.hasHighS())return!1;const{r:N,s:q}=I,H=K(w),O=i.inv(q),V=i.create(H*O),j=i.create(N*O),se=r.BASE.multiplyUnsafe(V).add(P.multiplyUnsafe(j));return se.is0()?!1:i.create(se.x)===N}catch{return!1}}function L(x,w,v={}){const{prehash:A}=ot(v,p);return w=J(w,A),M.fromBytes(x,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:u,utils:g,lengths:f,Point:r,sign:ie,verify:$,recoverPublicKey:L,Signature:M,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")]]},Wt=BigInt(2);function Jr(r){const e=gt.p,s=BigInt(3),t=BigInt(6),o=BigInt(11),n=BigInt(22),i=BigInt(23),a=BigInt(44),c=BigInt(88),l=r*r*r%e,d=l*l*r%e,u=oe(d,s,e)*d%e,g=oe(u,s,e)*d%e,f=oe(g,Wt,e)*l%e,p=oe(f,o,e)*f%e,b=oe(p,n,e)*p%e,y=oe(b,a,e)*b%e,E=oe(y,c,e)*y%e,D=oe(E,a,e)*b%e,U=oe(D,s,e)*d%e,M=oe(U,i,e)*p%e,B=oe(M,t,e)*l%e,K=oe(B,Wt,e);if(!ct.eql(ct.sqr(K),r))throw new Error("Cannot find square root");return K}const ct=Ze(gt.p,{sqrt:Jr}),Qr=jr(gt,{Fp:ct,endo:Xr}),eo=Zr(Qr,Er),to=BigInt(0),ke=BigInt(1),so=BigInt(2),ro=BigInt(7),oo=BigInt(256),no=BigInt(113),As=[],Ts=[],Cs=[];for(let r=0,e=ke,s=1,t=0;r<24;r++){[s,t]=[t,(2*s+3*t)%5],As.push(2*(5*t+s)),Ts.push((r+1)*(r+2)/2%64);let o=to;for(let n=0;n<7;n++)e=(e<<ke^(e>>ro)*no)%oo,e&so&&(o^=ke<<(ke<<BigInt(n))-ke);Cs.push(o)}const ks=gr(Cs,!0),io=ks[0],ao=ks[1],qt=(r,e,s)=>s>32?mr(r,e,s):xr(r,e,s),Vt=(r,e,s)=>s>32?yr(r,e,s):wr(r,e,s);function co(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],u=qt(l,d,1)^s[a],g=Vt(l,d,1)^s[a+1];for(let f=0;f<50;f+=10)r[i+f]^=u,r[i+f+1]^=g}let o=r[2],n=r[3];for(let i=0;i<24;i++){const a=Ts[i],c=qt(o,n,a),l=Vt(o,n,a),d=As[i];o=r[d],n=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]^=io[t],r[1]^=ao[t]}Te(s)}class xt{constructor(e,s,t,o=!1,n=24){S(this,"state");S(this,"pos",0);S(this,"posOut",0);S(this,"finished",!1);S(this,"state32");S(this,"destroyed",!1);S(this,"blockLen");S(this,"suffix");S(this,"outputLen");S(this,"enableXOF",!1);S(this,"rounds");if(this.blockLen=e,this.suffix=s,this.outputLen=t,this.enableXOF=o,this.rounds=n,pe(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ir(this.state)}clone(){return this._cloneInto()}keccak(){Ot(this.state32),co(this.state32,this.rounds),Ot(this.state32),this.posOut=0,this.pos=0}update(e){Ae(this),F(e);const{blockLen:s,state:t}=this,o=e.length;for(let n=0;n<o;){const i=Math.min(s-this.pos,o-n);for(let a=0;a<i;a++)t[this.pos++]^=e[n++];this.pos===s&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:s,pos:t,blockLen:o}=this;e[t]^=s,s&128&&t===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){Ae(this,!1),F(e),this.finish();const s=this.state,{blockLen:t}=this;for(let o=0,n=e.length;o<n;){this.posOut>=t&&this.keccak();const i=Math.min(t-this.posOut,n-o);e.set(s.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=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 pe(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,Te(this.state)}_cloneInto(e){const{blockLen:s,suffix:t,outputLen:o,rounds:n,enableXOF:i}=this;return e||(e=new xt(s,t,o,i,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=t,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}}const lo=(r,e,s,t={})=>rs(()=>new xt(e,r,s),t),Kt=lo(1,136,32);class uo{async verifyJWT(e,s){try{const t=this.decodeJWT(e);h.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat,"현재 시간":Math.floor(Date.now()/1e3)});const o=Math.floor(Date.now()/1e3);return t.exp&&t.exp<o?(h.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:o,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1}):t.sub?(h.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미구현)"),{payload:t,valid:!0,signatureVerified:!1}):(h.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1})}catch(t){throw h.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return Ls.decodeJwt(e)}recoverPersonalSignSigner(e,s){const t=new TextEncoder().encode(e),o=new TextEncoder().encode(`Ethereum Signed Message:
|
|
2
|
+
${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);const i=Kt(n),a=s.startsWith("0x")?s.slice(2):s;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=ho(a),l=c.slice(0,32),d=c.slice(32,64),u=c[64],g=u>=27?u-27:u,b=new eo.Signature(zt(l),zt(d)).addRecoveryBit(g).recoverPublicKey(i).toBytes(!1).slice(1),y=Kt(b);return"0x"+Oe(y.slice(12))}}function ho(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 po=3e4;class fo{async request(e){const s=new AbortController,t=setTimeout(()=>s.abort(),e.timeoutMs??po);try{const o=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 n;const i=await o.text();try{n=i?JSON.parse(i):null}catch{n={_raw:i}}return{status:o.status,data:n,headers:Object.fromEntries(o.headers.entries())}}finally{clearTimeout(t)}}}class wt{static generateState(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,s=>s.toString(16).padStart(2,"0")).join("")}openAuth(e){return new Promise((s,t)=>{const o=Math.max(e.width??500,500),n=Math.max(e.height??700,700),i=window.screenX+(window.outerWidth-o)/2,a=window.screenY+(window.outerHeight-n)/2,c=wt.generateState(),l=e.authUrl.includes("?")?"&":"?",d=`${e.authUrl}${l}state=${c}`,u=window.open(d,"CROSSx OAuth",`width=${o},height=${n},left=${i},top=${a}`);if(!u){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const g=setTimeout(()=>{h.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),U(),t(new Error("Authentication timeout"))},5*60*1e3),f=10,p=30;let b=0,y=null;const E=()=>{clearInterval(D),h.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+p+"초간 대기합니다"),y=setTimeout(()=>{U(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},p*1e3)},D=setInterval(()=>{b++;try{u.closed&&(b<=f?E():(U(),t(new Error("로그인이 취소되었습니다"))))}catch{E()}},1e3),U=()=>{clearTimeout(g),clearInterval(D),y&&clearTimeout(y),window.removeEventListener("message",M)},M=B=>{var le,fe,J,me,ie,$,L;if(B.origin!==e.expectedOrigin)return;U(),h.log("[CROSSx] OAuth postMessage 수신 — status:",B.data.status);const K=B.data.state??((le=B.data.data)==null?void 0:le.state);if(!K||K!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(B.data.status==="success"){const x=((fe=B.data.data)==null?void 0:fe.accessToken)||((J=B.data.data)==null?void 0:J.idToken);h.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!((me=B.data.data)!=null&&me.accessToken),hasIdToken:!!((ie=B.data.data)!=null&&ie.idToken)}),x?s(x):(h.error("[CROSSx] 토큰을 찾을 수 없음:",B.data),t(new Error("Token not found in response")))}else h.error("[CROSSx] OAuth 실패:",($=B.data.data)==null?void 0:$.error),t(new Error(((L=B.data.data)==null?void 0:L.error)||"Authentication failed"))};window.addEventListener("message",M)})}}const Re="crossx_wallet_data",Ee="crossx_mock_pw_hash";class _o{constructor(e,s){this.storage=e,this.passwordStore=s??null}async checkWallet(){if(this.migrateScenario!==void 0)return h.log("[Mock] checkWallet → migration_required"),"migration_required";const s=await this.storage.get(Re)?"exists":"not_found";return h.log(`[Mock] checkWallet → ${s}`),s}async getOrCreateWallet(e){var s;try{const t=await this.storage.get(Re);if(t)return t;const o={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Re,o);const n=(s=this.passwordStore)==null?void 0:s.get();return n&&(await this.storage.set(Ee,n),h.log("[Mock] 지갑 생성 — 비밀번호 저장됨")),o}catch(t){throw new m(_.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const s=await this.storage.get(Re);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 h.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+5*6e4).toISOString()}}async signMessage(e,s,t,o=0,n,i){return h.log(`[Mock] signMessage chainId=${s} index=${o} uuid=${n} from=${i}: "${t}"`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,s,t,o=0,n,i){return h.log(`[Mock] signTypedData chainId=${s} index=${o} uuid=${n} from=${i}`),{chainId:s,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,s,t,o=0,n){h.log(`[Mock] signTransaction chainId=${s} index=${o} uuid=${n}:`,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,o){return h.log(`[Mock] sendTransaction chainId=${s} uuid=${o}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPassword(e){var t;if(h.log("[Mock] verifyPassword"),this.passwordScenario==="wrong")return!1;const s=await this.storage.get(Ee);return s&&s!==e?!1:(s||await this.storage.set(Ee,e),(t=this.passwordStore)==null||t.set(e),h.log("[Mock] verifyPassword → 성공"),!0)}async changePassword(e,s){var n;if(h.log("[Mock] changePassword"),this.passwordScenario==="wrong")throw new m(_.PASSWORD_WRONG,"Incorrect password.");const t=(n=this.passwordStore)==null?void 0:n.get(),o=await this.storage.get(Ee);if(o&&t&&o!==t)throw new m(_.PASSWORD_WRONG,"Incorrect password.");await this.storage.set(Ee,s),h.log("[Mock] changePassword 완료")}async migrateWallet(e,s){var n;if(h.log(`[Mock] migrateWallet pin=${e} sub=${s}`),this.migrateScenario==="wrong_pin")throw new m(_.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new m(_.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(Re,t);const o=(n=this.passwordStore)==null?void 0:n.get();return o&&(await this.storage.set(Ee,o),h.log("[Mock] 마이그레이션 — 비밀번호 저장됨")),t}async getShareC(){return h.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyPin(e,s){return h.log("[Mock] verifyPin"),{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 Ke{constructor(e,s,t,o,n){this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=s,this.transport=t,this.tokenStore=o,this.passwordStore=n??null}getPassword(){var e;return((e=this.passwordStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}getAuthToken(){const e=this.tokenStore.get();if(!e)throw new m(_.AUTH_NOT_AUTHENTICATED,"인증 토큰을 찾을 수 없습니다. 먼저 로그인해 주세요.");return e}async request(e,s,t){var a,c;const o=this.getAuthToken(),n=`${this.baseUrl}${s}`,i={Authorization:`Bearer ${o}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const d=(await this.transport.request({url:n,method:e,headers:i,body:t??void 0})).data;if(d&&typeof d.code=="number"){if(d.code<0||d.code>=400){const u=d.message||d.data||"API 요청에 실패했습니다";h.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:d.code,message:u,url:n,method:e,fullResponse:d});const g=Ke.mapGatewayError(d.code,d.data),f=Ke.getGatewayErrorMessage(d.code,u),p=new m(g,f,d.data??void 0);throw p.gatewayCode=d.code,p.gatewayMessage=u,p}return h.log("[CROSSx] Wallet Gateway API 성공:",{code:d.code,url:n,method:e}),d.data??d}return d}catch(l){if(l instanceof m)throw l;if((a=l.response)!=null&&a.data){const d=l.response.data,u=d.message||d.data||"API 요청에 실패했습니다",g=d.code||"UNKNOWN";throw h.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:g,message:u,url:n,method:e,status:(c=l.response)==null?void 0:c.status}),new m(_.UNKNOWN_ERROR,`Wallet Gateway 오류 (${g}): ${u}`)}throw l}}async checkWallet(){h.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return h.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,h.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",s)):(h.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),s=await this.checkWallet(),this._walletStatusCache=null),s==="migration_required")throw h.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new m(_.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(s==="exists"){h.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const n=await this.getAddress(e,0);return h.log("[CROSSx] 주소 조회 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}h.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePassword()},o=await this.request("POST","/mnemonic/create",t);return h.log("[CROSSx] /mnemonic/create 완료 — address:",o.address),{id:e,address:o.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.requirePassword(),index:s};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${s}`}}async prepare(e,s){let t;switch(e){case"sign":case"send":if(!s.tx)throw new m(_.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(s.tx)};break;case"sign-message":if(!s.message)throw new m(_.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:s.message},s.from&&(t.from=s.from);break;case"sign-typed-data":if(!s.typedData)throw new m(_.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:s.typedData},s.from&&(t.from=s.from);break}const o={action:e,params:t},n=await this.request("POST","/mnemonic/prepare",o);return{uuid:n.uuid,expiresAt:n.expiresAt}}async signMessage(e,s,t,o,n,i){const a={message:t,password:this.requirePassword()};n&&(a.uuid=n),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,o,n,i){const a={typedData:t,password:this.requirePassword()};n&&(a.uuid=n),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,o,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePassword()};n&&(i.uuid=n);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,o){const n={unsignedTx:this.buildUnsignedTx(t),password:this.requirePassword()};return o&&(n.uuid=o),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(s)}`,n)).txHash}}async migrateWallet(e,s){h.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출 — sub:",s);const t={recoveryPin:e,sub:s,password:this.requirePassword()},o=await this.request("POST","/mnemonic/migrate",t);return h.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",o.address),{id:s,address:o.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const s={confirmation:e,password:this.requirePassword()};await this.request("POST","/mnemonic/withdraw",s)}async verifyPassword(e){const s={password:e};return(await this.request("POST","/mnemonic/verify-password",s)).verified}async changePassword(e,s){const t={password:this.requirePassword(),newPassword:s};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePassword()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyPin(e,s){const t={recoveryPin:e,sub:s};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePassword(){const e=this.getPassword();if(!e)throw new m(_.PASSWORD_NOT_SET,"비밀번호가 설정되지 않았습니다. 비밀번호를 입력해 주세요.");return e}static mapGatewayError(e,s){switch(e){case-10002:return _.AUTH_NOT_AUTHENTICATED;case-10001:case-10009:return _.UNKNOWN_ERROR;case-10006:return _.GATEWAY_INTERNAL_ERROR;case-10008:return _.GATEWAY_LOCK_CONFLICT;case-10010:return _.MIGRATION_FAILED;case-10012:return _.MIGRATION_BACKUP_EXISTS;case-10027:return _.MIGRATION_PIN_LOCKED;case-10022:return _.PROJECT_NOT_REGISTERED;case-10023:return _.PROJECT_ID_MISSING;case-10024:return _.ORIGIN_NOT_ALLOWED;case-10028:return _.PASSWORD_WRONG;case-10029:return _.PASSWORD_COMPLEXITY;case-10030:return _.WALLET_INCONSISTENT_STATE;case-10026:return _.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return _.PREPARE_FAILED;case-10016:return _.PREPARE_EXPIRED;case-10017:case-10018:return _.PREPARE_MISMATCH;default:return _.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 password. Please try again.";case-10029:return"Password does not meet complexity requirements. Please use a stronger password.";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 Pe{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=Pe.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(o=>o.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?tr:er;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,s){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=s}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const s=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new m(Pe.mapErrorCode(e.code),s)}}fallbackOrThrow(e){const s=Pe.fallbackChains().find(t=>t.chainId===e);if(s)return s;throw new m(_.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 _.CHAIN_NOT_SUPPORTED;case-10021:return _.INVALID_CHAIN;case-10022:return _.PROJECT_NOT_REGISTERED;case-10023:return _.PROJECT_ID_MISSING;case-10024:return _.APP_IDENTIFIER_MISSING;case-10025:return _.INVALID_APP_TYPE;default:return _.UNKNOWN_ERROR}}}const jt="__crossx-confirm-style",z="__crossx-confirm-overlay",go={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 Yt(r,e){const s=go[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 xo=`
|
|
3
3
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
4
4
|
|
|
5
|
-
#${
|
|
5
|
+
#${z} {
|
|
6
6
|
position: fixed;
|
|
7
7
|
inset: 0;
|
|
8
8
|
z-index: 2147483647;
|
|
@@ -1135,7 +1135,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1135
1135
|
|
|
1136
1136
|
/* ── Mobile bottom sheet ───────────────────────────────────── */
|
|
1137
1137
|
@media (max-width: 480px) {
|
|
1138
|
-
#${
|
|
1138
|
+
#${z} { align-items: flex-end; }
|
|
1139
1139
|
.__crossx-card {
|
|
1140
1140
|
width: 100%;
|
|
1141
1141
|
max-width: 100%;
|
|
@@ -1218,7 +1218,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1218
1218
|
|
|
1219
1219
|
/* ── Landscape for signing/transaction modals ──────────── */
|
|
1220
1220
|
@media (orientation: landscape) and (max-height: 500px) {
|
|
1221
|
-
#${
|
|
1221
|
+
#${z} { align-items: center !important; overflow: hidden; }
|
|
1222
1222
|
.__crossx-card--send-tx,
|
|
1223
1223
|
.__crossx-card--sign-tx,
|
|
1224
1224
|
.__crossx-card--sign-msg,
|
|
@@ -1357,7 +1357,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1357
1357
|
.__crossx-card--password .__crossx-pw-notice-title { font-size: 18px; }
|
|
1358
1358
|
.__crossx-card--password .__crossx-pw-notice-item { padding: 12px 14px; }
|
|
1359
1359
|
}
|
|
1360
|
-
`;function ce(){let r=document.getElementById(
|
|
1360
|
+
`;function ce(){let r=document.getElementById(jt);r||(r=document.createElement("style"),r.id=jt,document.head.appendChild(r)),r.textContent=xo}function X(r){return r?r.length<=13?r:`${r.slice(0,6)}…${r.slice(-4)}`:"—"}function wo(r,e="CROSS",s=18){if(!r||r==="0x"||r==="0x0")return null;try{const t=BigInt(r);if(t===0n)return null;const o=lt(t,s);return o==="0"?null:`${o} ${e}`}catch{return null}}const Zt={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)&&Zt[e]?Zt[e]:r}function lt(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,o=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return o?`${s}.${o}`:`${s}`}catch{return r}}function mo(r){try{return BigInt(r).toLocaleString()}catch{return r}}function yo(r){const{gasLimit:e,gasPrice:s,maxFeePerGas:t,maxPriorityFeePerGas:o,nativeSymbol:n="ETH",nativeDecimals:i=18}=r;if(!e)return null;try{const a=BigInt(e),c=mo(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${lt(l,i)} ${n}`,maxFeeGwei:nt(t),maxPriorityFeeGwei:o?nt(o):void 0,gasLimitFormatted:c}}if(s){const l=a*BigInt(s);return{isDynamic:!1,estTxFee:`${lt(l,i)} ${n}`,gasPriceGwei:nt(s),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function Ps(r){const e=yo(r);if(!e)return W("Estimated fee","<span>—</span>");let s=W("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(s+=W("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(s+=W("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(s+=W("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(s+=W("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),s}const he=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1361
1361
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1362
1362
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1363
1363
|
</svg>`,te=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
@@ -1376,12 +1376,12 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1376
1376
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
1377
1377
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
1378
1378
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
1379
|
-
</svg>`;function re(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function
|
|
1379
|
+
</svg>`;function re(r){return[`--cx-bg:${r.bg}`,`--cx-border:${r.border}`,`--cx-title:${r.titleColor}`,`--cx-subtitle:${r.subtitleColor}`,`--cx-label:${r.labelColor}`,`--cx-value:${r.valueColor}`,`--cx-pill-bg:${r.pillBg}`,`--cx-pill-from:${r.pillFromColor}`,`--cx-pill-amt:${r.pillAmtColor}`,`--cx-divider:${r.divider}`,`--cx-close:${r.closeColor}`,`--cx-close-hover:${r.closeHoverBg}`,`--cx-copy:${r.copyColor}`,`--cx-input-bg:${r.inputBg}`,`--cx-input-border:${r.inputBorder}`,`--cx-hint:${r.hintColor}`,`--cx-surface-subtle:${r.surfaceSubtle}`,`--cx-primary:${r.primary}`,`--cx-primary-glow:${r.primaryGlow}`,`--cx-secondary:${r.secondary}`,`--cx-error:${r.errorColor}`,`--cx-on-primary:${r.onPrimary}`].join(";")}function W(r,e){return`
|
|
1380
1380
|
<div class="__crossx-row">
|
|
1381
1381
|
<span class="__crossx-row-label">${r}</span>
|
|
1382
1382
|
<div class="__crossx-row-value">${e}</div>
|
|
1383
1383
|
</div>`}function Eo(r,e){const s=e,t=Xe(),o=r.to?`<span class="__crossx-addr-text">${X(r.to)}</span>
|
|
1384
|
-
<button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${he}</button>`:"<span>—</span>",n=Ps(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=
|
|
1384
|
+
<button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${he}</button>`:"<span>—</span>",n=Ps(r),i=r.data&&r.data!=="0x"?r.data:"0x",a=document.createElement("div");return a.id=z,a.innerHTML=`
|
|
1385
1385
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${re(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1386
1386
|
<div class="__crossx-header">
|
|
1387
1387
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1401,8 +1401,8 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1401
1401
|
<p class="__crossx-warning">After you sign, changes or cancellations are not possible.</p>
|
|
1402
1402
|
<hr class="__crossx-divider">
|
|
1403
1403
|
<div class="__crossx-rows">
|
|
1404
|
-
${
|
|
1405
|
-
${
|
|
1404
|
+
${W("To",o)}
|
|
1405
|
+
${W("Network",`<span>${Rs(r.chainId)}</span>`)}
|
|
1406
1406
|
${n}
|
|
1407
1407
|
</div>
|
|
1408
1408
|
</div>
|
|
@@ -1415,7 +1415,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1415
1415
|
</div>
|
|
1416
1416
|
</div>
|
|
1417
1417
|
`,a}function Io(r,e){const s=e,t=r.nativeSymbol??"ETH",o=r.nativeDecimals??18,n=Xe(),i=r.to?`<span class="__crossx-addr-text">${X(r.to)}</span>
|
|
1418
|
-
<button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${he}</button>`:"<span>—</span>",a=Ps(r),l=wo(r.value,t,o)??"—",d=document.createElement("div");return d.id=
|
|
1418
|
+
<button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${he}</button>`:"<span>—</span>",a=Ps(r),l=wo(r.value,t,o)??"—",d=document.createElement("div");return d.id=z,d.innerHTML=`
|
|
1419
1419
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${re(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1420
1420
|
<div class="__crossx-header">
|
|
1421
1421
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
@@ -1428,8 +1428,8 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1428
1428
|
</p>
|
|
1429
1429
|
<div class="__crossx-body-cols">
|
|
1430
1430
|
<div class="__crossx-rows">
|
|
1431
|
-
${
|
|
1432
|
-
${
|
|
1431
|
+
${W("To",i)}
|
|
1432
|
+
${W("Network",`<span>${Rs(r.chainId)}</span>`)}
|
|
1433
1433
|
${a}
|
|
1434
1434
|
</div>
|
|
1435
1435
|
<div class="__crossx-pill">
|
|
@@ -1440,13 +1440,13 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1440
1440
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
1441
1441
|
</div>
|
|
1442
1442
|
</div>
|
|
1443
|
-
`,d}function Xe(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function T(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ao(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function To(r){if(typeof r=="string")return T(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return T(JSON.stringify(r))}catch{return String(r)}}function Co(r,e){const s=
|
|
1444
|
-
<button class="__crossx-copy-btn" data-copy="${T(r.from)}" title="Copy address">${he}</button>`),t=r.to?
|
|
1445
|
-
<button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${he}</button>`):"",o=r.amount?
|
|
1443
|
+
`,d}function Xe(){var r;try{return((r=window.location)==null?void 0:r.hostname)||"This site"}catch{return"This site"}}function T(r){return r.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function Ao(r){return typeof r=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(r)}function To(r){if(typeof r=="string")return T(r);if(typeof r=="number"||typeof r=="bigint"||typeof r=="boolean")return String(r);try{return T(JSON.stringify(r))}catch{return String(r)}}function Co(r,e){const s=W("From",`<span class="__crossx-addr-text">${X(r.from)}</span>
|
|
1444
|
+
<button class="__crossx-copy-btn" data-copy="${T(r.from)}" title="Copy address">${he}</button>`),t=r.to?W("To",`<span class="__crossx-addr-text">${X(r.to)}</span>
|
|
1445
|
+
<button class="__crossx-copy-btn" data-copy="${T(r.to)}" title="Copy address">${he}</button>`):"",o=r.amount?W("Transfer",`<span>${T(r.amount)}</span>`):"",n=r.fees?W("Tx Fee",`<span>${T(r.fees)}</span>`):"",i=r.txHash?W("Tx Hash",`<span class="__crossx-addr-text">${X(r.txHash)}</span>
|
|
1446
1446
|
<button class="__crossx-copy-btn" data-copy="${T(r.txHash)}" title="Copy hash">${he}</button>`):"",a=r.total?`<div class="__crossx-total-pill">
|
|
1447
1447
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1448
1448
|
<span class="__crossx-total-amount">${T(r.total)}</span>
|
|
1449
|
-
</div>`:"",c=document.createElement("div");return c.id=
|
|
1449
|
+
</div>`:"",c=document.createElement("div");return c.id=z,c.innerHTML=`
|
|
1450
1450
|
<div class="__crossx-card __crossx-card--migration" style="${re(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1451
1451
|
<div class="__crossx-header">
|
|
1452
1452
|
<p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
|
|
@@ -1465,7 +1465,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1465
1465
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">All Done</button>
|
|
1466
1466
|
</div>
|
|
1467
1467
|
</div>
|
|
1468
|
-
`,c}function ko(r,e){const s=document.createElement("div");return s.id=
|
|
1468
|
+
`,c}function ko(r,e){const s=document.createElement("div");return s.id=z,s.innerHTML=`
|
|
1469
1469
|
<div class="__crossx-card __crossx-card--migration" style="${re(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1470
1470
|
<div class="__crossx-header">
|
|
1471
1471
|
<p class="__crossx-title" id="__crossx-ttl">Waiting for confirmation</p>
|
|
@@ -1478,9 +1478,9 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1478
1478
|
</div>
|
|
1479
1479
|
</div>
|
|
1480
1480
|
</div>
|
|
1481
|
-
`,s}function Ro(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",o=e.status==="timeout",n=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(n){const p=o?So:t?"":vo,b=o?"Transaction timeout":t?"Transaction complete":"Transaction failed";p?(n.style.display="flex",n.style.alignItems="center",n.style.gap="8px",n.innerHTML=`${p}<span>${b}</span>`):n.textContent=b}if(i&&!r.querySelector("#__crossx-close-btn")){const p=document.createElement("button");p.className="__crossx-close",p.id="__crossx-close-btn",p.setAttribute("aria-label","Close"),p.innerHTML=te,i.appendChild(p)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?
|
|
1482
|
-
<button class="__crossx-copy-btn" data-copy="${T(e.from)}" title="Copy address">${he}</button>`):"",l=e.to?
|
|
1483
|
-
<button class="__crossx-copy-btn" data-copy="${T(e.to)}" title="Copy address">${he}</button>`):"",d=e.amount?
|
|
1481
|
+
`,s}function Ro(r,e,s){const t=e.status!=="reverted"&&e.status!=="timeout",o=e.status==="timeout",n=r.querySelector("#__crossx-ttl"),i=r.querySelector(".__crossx-header");if(n){const p=o?So:t?"":vo,b=o?"Transaction timeout":t?"Transaction complete":"Transaction failed";p?(n.style.display="flex",n.style.alignItems="center",n.style.gap="8px",n.innerHTML=`${p}<span>${b}</span>`):n.textContent=b}if(i&&!r.querySelector("#__crossx-close-btn")){const p=document.createElement("button");p.className="__crossx-close",p.id="__crossx-close-btn",p.setAttribute("aria-label","Close"),p.innerHTML=te,i.appendChild(p)}const a=r.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?W("From",`<span class="__crossx-addr-text">${X(e.from)}</span>
|
|
1482
|
+
<button class="__crossx-copy-btn" data-copy="${T(e.from)}" title="Copy address">${he}</button>`):"",l=e.to?W("To",`<span class="__crossx-addr-text">${X(e.to)}</span>
|
|
1483
|
+
<button class="__crossx-copy-btn" data-copy="${T(e.to)}" title="Copy address">${he}</button>`):"",d=e.amount?W("Transfer",`<span>${T(e.amount)}</span>`):"",u=e.fees?W("Tx Fee",`<span>${T(e.fees)}</span>`):"",g=e.txHash?W("Tx Hash",`<span class="__crossx-addr-text">${X(e.txHash)}</span>
|
|
1484
1484
|
<button class="__crossx-copy-btn" data-copy="${T(e.txHash)}" title="Copy hash">${he}</button>`):"",f=e.total?`<div class="__crossx-total-pill">
|
|
1485
1485
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1486
1486
|
<span class="__crossx-total-amount">${T(e.total)}</span>
|
|
@@ -1490,11 +1490,11 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1490
1490
|
${l}
|
|
1491
1491
|
${d}
|
|
1492
1492
|
${u}
|
|
1493
|
-
${
|
|
1493
|
+
${g}
|
|
1494
1494
|
</div>
|
|
1495
1495
|
${f}
|
|
1496
1496
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1497
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",b=>{var E;b.stopPropagation();const y=p.dataset.copy;y&&((E=navigator.clipboard)==null||E.writeText(y).catch(()=>{}))})})}function Po(r,e){const s=e,t=Xe(),o=T(r.message),n=document.createElement("div");return n.id=
|
|
1497
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(p=>{p.addEventListener("click",b=>{var E;b.stopPropagation();const y=p.dataset.copy;y&&((E=navigator.clipboard)==null||E.writeText(y).catch(()=>{}))})})}function Po(r,e){const s=e,t=Xe(),o=T(r.message),n=document.createElement("div");return n.id=z,n.innerHTML=`
|
|
1498
1498
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${re(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1499
1499
|
<div class="__crossx-header">
|
|
1500
1500
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1531,7 +1531,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1531
1531
|
<div class="__crossx-td-row">
|
|
1532
1532
|
<span class="__crossx-td-label">${T(l)}</span>
|
|
1533
1533
|
<div class="__crossx-td-value">${f}</div>
|
|
1534
|
-
</div>`}const c=document.createElement("div");return c.id=
|
|
1534
|
+
</div>`}const c=document.createElement("div");return c.id=z,c.innerHTML=`
|
|
1535
1535
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${re(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1536
1536
|
<div class="__crossx-header">
|
|
1537
1537
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
@@ -1564,7 +1564,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1564
1564
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
1565
1565
|
</svg>`;function Lo(r,e,s){const t=s==null?void 0:s.toLowerCase(),o=r.map(i=>{const a=t&&i.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${i.index}" data-wallet-address="${T(i.address)}">
|
|
1566
1566
|
<span class="__crossx-wallet-addr">${X(i.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
1567
|
-
</button>`}).join(""),n=document.createElement("div");return n.id=
|
|
1567
|
+
</button>`}).join(""),n=document.createElement("div");return n.id=z,n.innerHTML=`
|
|
1568
1568
|
<div class="__crossx-card __crossx-card--migration __crossx-card--wallet-selector" style="${re(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1569
1569
|
<div class="__crossx-header">
|
|
1570
1570
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -1603,7 +1603,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1603
1603
|
<path d="M20.5 38.5c4.94 0 9.09-1.64 12.12-4.44l-5.91-4.57c-1.64 1.1-3.73 1.75-6.21 1.75-4.77 0-8.82-3.22-10.26-7.55H4.16v4.72A18.49 18.49 0 0 0 20.5 38.5z" fill="#34A853"/>
|
|
1604
1604
|
<path d="M10.24 23.69A11.16 11.16 0 0 1 9.66 20c0-1.28.22-2.52.58-3.69v-4.72H4.16A18.49 18.49 0 0 0 2 20c0 2.97.71 5.78 1.97 8.28l6.27-4.59z" fill="#FBBC05"/>
|
|
1605
1605
|
<path d="M20.5 8.76c2.69 0 5.1.92 7 2.73l5.24-5.24C29.58 3.36 25.43 1.5 20.5 1.5A18.49 18.49 0 0 0 4.16 11.59l6.08 4.72C11.68 11.98 15.73 8.76 20.5 8.76z" fill="#EA4335"/>
|
|
1606
|
-
</svg>`;function $o(r){const e=r,s=document.createElement("div");return s.id=
|
|
1606
|
+
</svg>`;function $o(r){const e=r,s=document.createElement("div");return s.id=z,s.innerHTML=`
|
|
1607
1607
|
<div class="__crossx-card __crossx-card--migration" style="${re(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1608
1608
|
<div class="__crossx-header">
|
|
1609
1609
|
<div style="display:flex;flex-direction:column;gap:4px;padding-right:36px;">
|
|
@@ -1630,7 +1630,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1630
1630
|
</p>
|
|
1631
1631
|
</div>
|
|
1632
1632
|
</div>
|
|
1633
|
-
`,s}function Bo(r){const e=r,s=document.createElement("div");return s.id=
|
|
1633
|
+
`,s}function Bo(r){const e=r,s=document.createElement("div");return s.id=z,s.innerHTML=`
|
|
1634
1634
|
<div class="__crossx-card __crossx-card--migration" style="${re(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1635
1635
|
<div class="__crossx-header">
|
|
1636
1636
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -1650,7 +1650,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1650
1650
|
<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>
|
|
1651
1651
|
</div>
|
|
1652
1652
|
</div>
|
|
1653
|
-
`,s}function Uo(r,e){const s=r,{errorMessage:t,attemptCount:o,maxAttempts:n=5}=e??{},i=!!t,a=i?" --error":"",c=o!=null&&o>0?`<p class="__crossx-pin-attempt">${o}/${n}</p>`:"",l=o!=null&&o>=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>`:"",u=document.createElement("div");return u.id=
|
|
1653
|
+
`,s}function Uo(r,e){const s=r,{errorMessage:t,attemptCount:o,maxAttempts:n=5}=e??{},i=!!t,a=i?" --error":"",c=o!=null&&o>0?`<p class="__crossx-pin-attempt">${o}/${n}</p>`:"",l=o!=null&&o>=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>`:"",u=document.createElement("div");return u.id=z,u.innerHTML=`
|
|
1654
1654
|
<div class="__crossx-card __crossx-card--migration" style="${re(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1655
1655
|
<div class="__crossx-header">
|
|
1656
1656
|
<p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
|
|
@@ -1670,7 +1670,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1670
1670
|
${d}
|
|
1671
1671
|
</div>
|
|
1672
1672
|
</div>
|
|
1673
|
-
`,u}function Ho(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"],o=s[e.getDay()],n=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${o}, ${n} ${i} ${a}:${c}`}function Fo(r,e,s){const t=r,o=e<=0,n=o?null:Date.now()+e*1e3,i=n?Ho(n):null,a=document.createElement("div");return a.id=
|
|
1673
|
+
`,u}function Ho(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"],o=s[e.getDay()],n=t[e.getMonth()],i=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${o}, ${n} ${i} ${a}:${c}`}function Fo(r,e,s){const t=r,o=e<=0,n=o?null:Date.now()+e*1e3,i=n?Ho(n):null,a=document.createElement("div");return a.id=z,a.innerHTML=`
|
|
1674
1674
|
<div class="__crossx-card __crossx-card--migration" style="${re(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1675
1675
|
<div class="__crossx-header">
|
|
1676
1676
|
<p class="__crossx-title" id="__crossx-ttl">Recover My Wallet</p>
|
|
@@ -1690,7 +1690,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1690
1690
|
</div>
|
|
1691
1691
|
</div>
|
|
1692
1692
|
</div>
|
|
1693
|
-
`,{overlay:a,startCountdown:l=>{if(o||!n)return()=>{};const u=setInterval(()=>{Date.now()>=n&&(clearInterval(u),l())},1e3);return()=>clearInterval(u)}}}const
|
|
1693
|
+
`,{overlay:a,startCountdown:l=>{if(o||!n)return()=>{};const u=setInterval(()=>{Date.now()>=n&&(clearInterval(u),l())},1e3);return()=>clearInterval(u)}}}const ze=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1694
1694
|
<path d="M15 12C15 13.6569 13.6569 15 12 15C10.3431 15 9 13.6569 9 12C9 10.3431 10.3431 9 12 9C13.6569 9 15 10.3431 15 12Z" fill="currentColor"/>
|
|
1695
1695
|
<path d="M21.8944 11.5528C19.7362 7.23635 15.9031 5 12 5C8.09687 5 4.26379 7.23635 2.10557 11.5528C1.96481 11.8343 1.96481 12.1657 2.10557 12.4472C4.26379 16.7637 8.09687 19 12 19C15.9031 19 19.7362 16.7637 21.8944 12.4472C22.0352 12.1657 22.0352 11.8343 21.8944 11.5528ZM12 17C9.03121 17 5.99806 15.3792 4.12966 12C5.99806 8.62078 9.03121 7 12 7C14.9688 7 18.0019 8.62078 19.8703 12C18.0019 15.3792 14.9688 17 12 17Z" fill="currentColor"/>
|
|
1696
1696
|
</svg>`,yt=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
@@ -1700,13 +1700,13 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1700
1700
|
<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"/>
|
|
1701
1701
|
</svg>`,Ue=`<svg width="9" height="7" viewBox="0 0 9 7" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1702
1702
|
<path d="M1 3.5L3.5 6L8 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
1703
|
-
</svg>`,
|
|
1703
|
+
</svg>`,Wo=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1704
1704
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
1705
|
-
</svg>`,
|
|
1705
|
+
</svg>`,qo=`<svg width="28" height="28" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
1706
1706
|
<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"/>
|
|
1707
|
-
</svg>`;function Vo(r){return{minLength:r.length>=8,uppercase:/[A-Z]/.test(r),number:/[0-9]/.test(r),special:/[^A-Za-z0-9]/.test(r)}}function Ko(r){return r.minLength&&r.uppercase&&r.number&&r.special}function
|
|
1707
|
+
</svg>`;function Vo(r){return{minLength:r.length>=8,uppercase:/[A-Z]/.test(r),number:/[0-9]/.test(r),special:/[^A-Za-z0-9]/.test(r)}}function Ko(r){return r.minLength&&r.uppercase&&r.number&&r.special}function zo(r){const s=[r.check1,r.check2,r.check3].map((t,o)=>`
|
|
1708
1708
|
<div class="__crossx-pw-notice-item" data-check-index="${o}" role="checkbox" aria-checked="false" tabindex="0">
|
|
1709
|
-
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${o}">${
|
|
1709
|
+
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${o}">${Wo}</div>
|
|
1710
1710
|
<span class="__crossx-pw-notice-item-text">${T(t)}</span>
|
|
1711
1711
|
</div>
|
|
1712
1712
|
`).join("");return`
|
|
@@ -1720,7 +1720,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1720
1720
|
<div class="__crossx-pw-fields __crossx-pw-fields--notice">
|
|
1721
1721
|
<div class="__crossx-pw-notice-header">
|
|
1722
1722
|
<div class="__crossx-pw-notice-title-row">
|
|
1723
|
-
<span class="__crossx-pw-notice-icon">${
|
|
1723
|
+
<span class="__crossx-pw-notice-icon">${qo}</span>
|
|
1724
1724
|
<p class="__crossx-pw-notice-title">${T(r.noticeTitle)}</p>
|
|
1725
1725
|
</div>
|
|
1726
1726
|
<p class="__crossx-pw-notice-desc">${T(r.noticeDesc)}</p>
|
|
@@ -1736,7 +1736,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1736
1736
|
</button>
|
|
1737
1737
|
</div>
|
|
1738
1738
|
<div class="__crossx-home-indicator"></div>
|
|
1739
|
-
`}function
|
|
1739
|
+
`}function jo(r,e){return`
|
|
1740
1740
|
<div class="__crossx-header">
|
|
1741
1741
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${T(r.title)}</p>
|
|
1742
1742
|
<p class="__crossx-pw-subtitle--tertiary">${T(r.subtitle)}</p>
|
|
@@ -1749,7 +1749,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1749
1749
|
<label class="__crossx-pw-label" for="__crossx-pw-new">${T(r.newPasswordLabel)}</label>
|
|
1750
1750
|
<div class="__crossx-pw-input-wrap" id="__crossx-pw-new-wrap">
|
|
1751
1751
|
<input class="__crossx-pw-input" id="__crossx-pw-new" type="password" autocomplete="new-password" />
|
|
1752
|
-
<button class="__crossx-pw-toggle" id="__crossx-pw-new-toggle" type="button" aria-label="Toggle visibility">${
|
|
1752
|
+
<button class="__crossx-pw-toggle" id="__crossx-pw-new-toggle" type="button" aria-label="Toggle visibility">${ze}</button>
|
|
1753
1753
|
</div>
|
|
1754
1754
|
</div>
|
|
1755
1755
|
<div class="__crossx-pw-rules" id="__crossx-pw-rules">
|
|
@@ -1774,7 +1774,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1774
1774
|
<label class="__crossx-pw-label" for="__crossx-pw-confirm">${T(r.confirmPasswordLabel)}</label>
|
|
1775
1775
|
<div class="__crossx-pw-input-wrap" id="__crossx-pw-confirm-wrap">
|
|
1776
1776
|
<input class="__crossx-pw-input" id="__crossx-pw-confirm" type="password" autocomplete="new-password" />
|
|
1777
|
-
<button class="__crossx-pw-toggle" id="__crossx-pw-confirm-toggle" type="button" aria-label="Toggle visibility">${
|
|
1777
|
+
<button class="__crossx-pw-toggle" id="__crossx-pw-confirm-toggle" type="button" aria-label="Toggle visibility">${ze}</button>
|
|
1778
1778
|
</div>
|
|
1779
1779
|
<p class="__crossx-pw-error-text" id="__crossx-pw-confirm-error" style="display:none;">${T(r.confirmError)}</p>
|
|
1780
1780
|
${e!=null&&e.errorMessage?`<p class="__crossx-pw-error-text">${T(e.errorMessage)}</p>`:""}
|
|
@@ -1785,7 +1785,7 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1785
1785
|
</button>
|
|
1786
1786
|
</div>
|
|
1787
1787
|
<div class="__crossx-home-indicator"></div>
|
|
1788
|
-
`}function Yo(r,e,s,t){const o=r,n=document.createElement("div");n.id=
|
|
1788
|
+
`}function Yo(r,e,s,t){const o=r,n=document.createElement("div");n.id=z;const i=document.createElement("div");return i.className="__crossx-card __crossx-card--password",i.setAttribute("style",re(o)),i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-labelledby","__crossx-ttl"),i.innerHTML=zo(e),n.appendChild(i),n}function Zo(r,e,s){var u;const t=r.querySelector("#__crossx-notice-submit"),o=Array.from(r.querySelectorAll(".__crossx-pw-notice-item")),n=new Set;t.removeAttribute("disabled");const i=t.dataset.nextLabel??"Next",a=t.dataset.submitLabel??"I Understand",c=()=>{const g=n.size===o.length;t.classList.toggle("--disabled",!g),t.textContent=g?a:i},l=(g,f)=>{if(n.has(f))return;const p=g.querySelector(`#__crossx-notice-check-${f}`);n.add(f),p.classList.add("--checked"),g.setAttribute("aria-checked","true"),c()},d=(g,f)=>{if(!n.has(f))return;const p=g.querySelector(`#__crossx-notice-check-${f}`);n.delete(f),p.classList.remove("--checked"),g.setAttribute("aria-checked","false"),c()};o.forEach(g=>{const f=parseInt(g.dataset.checkIndex??"0",10);g.addEventListener("click",()=>{n.has(f)?d(g,f):l(g,f)}),g.addEventListener("keydown",p=>{(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),n.has(f)?d(g,f):l(g,f))})}),t.addEventListener("click",()=>{if(n.size===o.length){s();return}const g=o.find(p=>{const b=parseInt(p.dataset.checkIndex??"0",10);return!n.has(b)});if(!g)return;const f=parseInt(g.dataset.checkIndex??"0",10);g.scrollIntoView({behavior:"smooth",block:"nearest"}),g.classList.add("--highlight"),setTimeout(()=>{g.classList.remove("--highlight"),l(g,f)},400)}),(u=r.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",e)}function Xo(r,e,s,t){var p;const o=r.querySelector("#__crossx-pw-new"),n=r.querySelector("#__crossx-pw-confirm"),i=r.querySelector("#__crossx-pw-new-toggle"),a=r.querySelector("#__crossx-pw-confirm-toggle"),c=r.querySelector("#__crossx-pw-confirm-wrap"),l=r.querySelector("#__crossx-pw-confirm-error"),d=r.querySelector("#__crossx-pw-submit"),u={minLength:r.querySelector("#__crossx-rule-minLength"),uppercase:r.querySelector("#__crossx-rule-uppercase"),number:r.querySelector("#__crossx-rule-number"),special:r.querySelector("#__crossx-rule-special")},g=()=>{const b=o.value,y=n.value,E=Vo(b),D=Ko(E);Object.keys(E).forEach(le=>{u[le].classList.toggle("--met",E[le])});const U=y.length>0,M=b===y,B=U&&!M;c.classList.toggle("--error",B),l.style.display=B?"block":"none";const K=D&&M&&y.length>0;d.disabled=!K,d.classList.toggle("--disabled",!K)},f=(b,y)=>{const E=b.type==="password";b.type=E?"text":"password",y.innerHTML=E?yt:ze};o.addEventListener("input",g),n.addEventListener("input",g),i.addEventListener("click",()=>f(o,i)),a.addEventListener("click",()=>f(n,a)),d.addEventListener("click",()=>{d.disabled||s(o.value)}),(p=r.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",t),o.addEventListener("keydown",b=>{b.key==="Escape"&&t()}),n.addEventListener("keydown",b=>{b.key==="Enter"&&!d.disabled&&s(o.value),b.key==="Escape"&&t()}),o.focus()}function Jo(r,e,s){const t=r,o=!!(s!=null&&s.errorMessage),n=document.createElement("div");return n.id=z,n.innerHTML=`
|
|
1789
1789
|
<div class="__crossx-card __crossx-card--password" style="${re(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1790
1790
|
<div class="__crossx-header">
|
|
1791
1791
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${T(e.title)}</p>
|
|
@@ -1812,4 +1812,4 @@ ${t.length}`),n=new Uint8Array(o.length+t.length);n.set(o,0),n.set(t,o.length);c
|
|
|
1812
1812
|
</div>
|
|
1813
1813
|
</div>
|
|
1814
1814
|
</div>
|
|
1815
|
-
`,n}function Qo(r,e,s,t,o){var f;const n=r.querySelector("#__crossx-pw-enter"),i=r.querySelector("#__crossx-pw-enter-toggle"),a=r.querySelector("#__crossx-pw-enter-wrap"),c=r.querySelector("#__crossx-pw-enter-error"),l=r.querySelector("#__crossx-pw-confirm-group"),d=r.querySelector("#__crossx-pw-submit");n.addEventListener("input",()=>{const p=n.value.length>0;d.disabled=!p,d.classList.toggle("--disabled",!p),p&&(a.classList.remove("--error"),c.style.display="none",l.classList.remove("--has-error"))}),i.addEventListener("click",()=>{const p=n.type==="password";n.type=p?"text":"password",i.innerHTML=p?je:yt});const u=p=>{c.textContent=p,c.style.display="",a.classList.add("--error"),l.classList.add("--has-error"),d.disabled=!1,d.classList.remove("--disabled")},_=()=>{if(d.disabled)return;const p=n.value;t?(d.disabled=!0,d.classList.add("--disabled"),t(p).then(b=>{b.ok?e(p):(u(b.error??"Incorrect password. Please try again."),n.focus())}).catch(b=>{o?o(b):s()})):e(p)};d.addEventListener("click",_),n.addEventListener("keydown",p=>{p.key==="Enter"&&_(),p.key==="Escape"&&s()}),(f=r.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",s),n.focus()}function en(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((n,i)=>{n.addEventListener("input",()=>{const a=n.value.replace(/\D/g,"");n.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)}),n.addEventListener("keydown",a=>{a.key==="Backspace"&&!n.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),n.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),n.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((u,_)=>{t[_]&&(t[_].value=u)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(o=t[0])==null||o.focus()}class tn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Yt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Yt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(o=>{var b;ce();const n=[...e],i=Lo(n,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(),o(y)},u=()=>{l(),o(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const E=y.dataset.walletAddress??"",D=parseInt(y.dataset.walletIndex??"0",10);d({address:E,index:D})})})})();const f=i.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.disabled=!0;try{const y=await s();n.push(y);const E=i.querySelector("#__crossx-wallet-list");if(E){const D=document.createElement("button");D.className="__crossx-wallet-item",D.dataset.walletIndex=String(y.index),D.dataset.walletAddress=y.address,D.innerHTML=`<span class="__crossx-wallet-addr">${X(y.address)}</span>`,D.addEventListener("click",()=>d(y)),E.appendChild(D),D.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(b=i.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",u),i.addEventListener("click",y=>{y.target===i&&u()});const p=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showLoginSelector(){return new Promise(e=>{var a,c,l;ce();const s=$o(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),o=d=>{t(),e(d)},n=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>o("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>o("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),s.addEventListener("click",d=>{d.target===s&&n()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",u=>u.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;ce();const s=Bo(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),o=()=>{t(),e("recover")},n=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",n),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),s.addEventListener("click",d=>{d.target===s&&n()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showPasswordSetupPrompt(e){return new Promise(s=>{ce();const t=this.messages,o={title:(t==null?void 0:t.passwordSetup_title)??"Create Password",headerSubtitle:(t==null?void 0:t.passwordNotice_headerSubtitle)??"Required for Transactions, PK/Mnemonic & Account Deletion.",noticeTitle:(t==null?void 0:t.passwordNotice_title)??"Password Setup Notice",noticeDesc:(t==null?void 0:t.passwordNotice_description)??"For your security, this password cannot be reset or recovered. Please ensure you have it backed up or memorized.",check1:(t==null?void 0:t.passwordNotice_check1)??"This password cannot be recovered if lost, and I have securely backed it up.",check2:(t==null?void 0:t.passwordNotice_check2)??"Losing this password may result in permanent loss of access to my account and all associated data.",check3:(t==null?void 0:t.passwordNotice_check3)??"No third party, including the support team, can recover or reset this password on my behalf.",nextButton:(t==null?void 0:t.passwordNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.passwordNotice_submitButton)??"I Understand"},n={title:(t==null?void 0:t.passwordSetup_title)??"Create Password",subtitle:(t==null?void 0:t.passwordSetup_subtitle)??"Password is only used to transfer your asset.",newPasswordLabel:(t==null?void 0:t.passwordSetup_newPasswordLabel)??"New Password",confirmPasswordLabel:(t==null?void 0:t.passwordSetup_confirmPasswordLabel)??"Confirm New Password",rule_minLength:(t==null?void 0:t.passwordSetup_rule_minLength)??"Over 8 letters",rule_uppercase:(t==null?void 0:t.passwordSetup_rule_uppercase)??"Include at least 1 uppercase letter",rule_number:(t==null?void 0:t.passwordSetup_rule_number)??"Include at least 1 number",rule_special:(t==null?void 0:t.passwordSetup_rule_special)??"Include at least 1 special character",confirmError:(t==null?void 0:t.passwordSetup_confirmError)??"Password is incorrect",submitButton:(t==null?void 0:t.passwordSetup_submitButton)??"Next"},i=Yo(this.tokens,o),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=p=>{l(),s(p)},u=()=>{l(),s(null)},_=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",_),u())};document.addEventListener("keydown",_);const f=i.querySelector(".__crossx-card");Zo(f,u,()=>{var p;f.innerHTML=zo(n,e),Xo(i,{},d,u),(p=i.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",u)}),i.addEventListener("click",p=>{p.target===i&&u()})})}showPasswordInputPrompt(e){return new Promise((s,t)=>{ce();const o=this.messages,n=(e==null?void 0:e.verifyMode)===!0,i={title:n?(o==null?void 0:o.verifyPassword_title)??"Verify Your Password":(o==null?void 0:o.passwordInput_title)??"Enter Password",subtitle:n?(o==null?void 0:o.verifyPassword_subtitle)??"To continue, please confirm your current password":(o==null?void 0:o.passwordInput_subtitle)??"Enter your password to continue.",passwordLabel:n?(o==null?void 0:o.verifyPassword_passwordLabel)??"Confirm Password":(o==null?void 0:o.passwordInput_passwordLabel)??"Password",submitButton:(o==null?void 0:o.passwordInput_submitButton)??"Confirm",error:(o==null?void 0:o.passwordInput_error)??"Incorrect password. Please try again."},a=Jo(this.tokens,i,e),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)},u=b=>{d(),s(b)},_=()=>{d(),s(null)},f=b=>{d(),t(b)};Qo(a,u,_,e==null?void 0:e.onSubmit,f),a.addEventListener("click",b=>{b.target===a&&_()});const p=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",p),_())};document.addEventListener("keydown",p)})}showPinInputPrompt(e){return new Promise(s=>{var a;ce();const t=Uo(this.tokens,e);document.body.appendChild(t);const o=()=>t.remove(),n=c=>{o(),s(c)},i=()=>{o(),s(null)};en(t,n,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showPinLockedPrompt(e,s){return new Promise(t=>{var l;ce();const{overlay:o,startCountdown:n}=Fo(this.tokens,e,s);document.body.appendChild(o);const i=()=>{c(),o.remove()},a=()=>{i(),t()},c=n(a);(l=o.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),o.addEventListener("click",d=>{d.target===o&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;ce();const t=Co(e,this.tokens);document.body.appendChild(t);const o=()=>t.remove(),n=()=>{o(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",n),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",n),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var _;d.stopPropagation();const u=l.dataset.copy;u&&((_=navigator.clipboard)==null||_.writeText(u).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&n()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{ce();const o=ko(e,this.tokens);document.body.appendChild(o);const n=()=>o.remove();let i=!1;const a=()=>{i||(i=!0,n(),t())},c=()=>{var d,u;(d=o.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(u=o.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),o.addEventListener("click",_=>{_.target===o&&a()});const l=_=>{_.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Ro(o,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;ce();let t;e.type==="sign-message"?t=Po(e,this.tokens):e.type==="sign-typed-data"?t=Oo(e,this.tokens):e.type==="sign"?t=Eo(e,this.tokens):t=Io(e,this.tokens),document.body.appendChild(t);const o=()=>t.remove(),n=()=>{o(),s(!0)},i=()=>{o(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",n),(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(u=>{u.addEventListener("click",_=>{var p;_.stopPropagation();const f=u.dataset.copy;f&&((p=navigator.clipboard)==null||p.writeText(f).catch(()=>{}))})}),t.addEventListener("click",u=>{u.target===t&&i()});const a=u=>{u.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class sn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function rn(r){r.debug;const e=Fe.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},n=s.authMode!=="cookie"&&Pt.isAvailable()?new Pt:new sr,i=new uo,a=new fo,c=new wt,l=new sn,d=new Qt;let u;r.useMockWallet?(h.log("[CROSSx] Mock Wallet Provider 사용"),u=new _o(n,d)):(h.log("[CROSSx] Remote Wallet Provider 사용"),u=new Ke(t,n,a,l,d));const _=new Pe(t,a),f=new tn(r.theme??"light",r.themeTokens);return new Ge(s,t,n,i,a,c,u,l,f,_,d)}exports.CROSSxError=m;exports.CROSSxEthereumProvider=Xt;exports.CROSSxSDK=Ge;exports.ChainId=Ds;exports.ErrorCode=g;exports.createCROSSxSDK=rn;
|
|
1815
|
+
`,n}function Qo(r,e,s,t,o){var f;const n=r.querySelector("#__crossx-pw-enter"),i=r.querySelector("#__crossx-pw-enter-toggle"),a=r.querySelector("#__crossx-pw-enter-wrap"),c=r.querySelector("#__crossx-pw-enter-error"),l=r.querySelector("#__crossx-pw-confirm-group"),d=r.querySelector("#__crossx-pw-submit");n.addEventListener("input",()=>{const p=n.value.length>0;d.disabled=!p,d.classList.toggle("--disabled",!p),p&&(a.classList.remove("--error"),c.style.display="none",l.classList.remove("--has-error"))}),i.addEventListener("click",()=>{const p=n.type==="password";n.type=p?"text":"password",i.innerHTML=p?ze:yt});const u=p=>{c.textContent=p,c.style.display="",a.classList.add("--error"),l.classList.add("--has-error"),d.disabled=!1,d.classList.remove("--disabled")},g=()=>{if(d.disabled)return;const p=n.value;t?(d.disabled=!0,d.classList.add("--disabled"),t(p).then(b=>{b.ok?e(p):(u(b.error??"Incorrect password. Please try again."),n.focus())}).catch(b=>{o?o(b):s()})):e(p)};d.addEventListener("click",g),n.addEventListener("keydown",p=>{p.key==="Enter"&&g(),p.key==="Escape"&&s()}),(f=r.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",s),n.focus()}function en(r,e,s){var o;const t=r.querySelectorAll(".__crossx-pin-input");t.forEach((n,i)=>{n.addEventListener("input",()=>{const a=n.value.replace(/\D/g,"");n.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)}),n.addEventListener("keydown",a=>{a.key==="Backspace"&&!n.value&&i>0&&(t[i-1].focus(),t[i-1].value=""),a.key==="Escape"&&s()}),n.addEventListener("keypress",a=>{/[0-9]/.test(a.key)||a.preventDefault()}),n.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((u,g)=>{t[g]&&(t[g].value=u)});const l=Math.min(c.length,3);t[l].focus(),c.length===4&&setTimeout(()=>e(c),200)})}),(o=t[0])==null||o.focus()}class tn{constructor(e="light",s){this.theme=e,this.overrides=s,this.tokens=Yt(e,s)}setTheme(e,s){this.theme=e,s!==void 0&&(this.overrides=s),this.tokens=Yt(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,s,t){return new Promise(o=>{var b;ce();const n=[...e],i=Lo(n,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(),o(y)},u=()=>{l(),o(null)};(()=>{i.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const E=y.dataset.walletAddress??"",D=parseInt(y.dataset.walletIndex??"0",10);d({address:E,index:D})})})})();const f=i.querySelector("#__crossx-add-wallet-btn");f&&f.addEventListener("click",async()=>{f.disabled=!0;try{const y=await s();n.push(y);const E=i.querySelector("#__crossx-wallet-list");if(E){const D=document.createElement("button");D.className="__crossx-wallet-item",D.dataset.walletIndex=String(y.index),D.dataset.walletAddress=y.address,D.innerHTML=`<span class="__crossx-wallet-addr">${X(y.address)}</span>`,D.addEventListener("click",()=>d(y)),E.appendChild(D),D.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{f.disabled=!1}}),(b=i.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",u),i.addEventListener("click",y=>{y.target===i&&u()});const p=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",p),u())};document.addEventListener("keydown",p)})}showLoginSelector(){return new Promise(e=>{var a,c,l;ce();const s=$o(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),o=d=>{t(),e(d)},n=()=>{t(),e(null)};(a=s.querySelector("#__crossx-apple-btn"))==null||a.addEventListener("click",()=>o("apple")),(c=s.querySelector("#__crossx-google-btn"))==null||c.addEventListener("click",()=>o("google")),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),s.addEventListener("click",d=>{d.target===s&&n()}),s.querySelectorAll(".__crossx-login-terms-link").forEach(d=>{d.addEventListener("click",u=>u.stopPropagation())});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showMigrationFoundPrompt(){return new Promise(e=>{var a,c,l;ce();const s=Bo(this.tokens);document.body.appendChild(s);const t=()=>s.remove(),o=()=>{t(),e("recover")},n=()=>{t(),e("skip")};(a=s.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),(c=s.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",n),(l=s.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",n),s.addEventListener("click",d=>{d.target===s&&n()});const i=d=>{d.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showPasswordSetupPrompt(e){return new Promise(s=>{ce();const t=this.messages,o={title:(t==null?void 0:t.passwordSetup_title)??"Create Password",headerSubtitle:(t==null?void 0:t.passwordNotice_headerSubtitle)??"Required for Transactions, PK/Mnemonic & Account Deletion.",noticeTitle:(t==null?void 0:t.passwordNotice_title)??"Password Setup Notice",noticeDesc:(t==null?void 0:t.passwordNotice_description)??"For your security, this password cannot be reset or recovered. Please ensure you have it backed up or memorized.",check1:(t==null?void 0:t.passwordNotice_check1)??"This password cannot be recovered if lost, and I have securely backed it up.",check2:(t==null?void 0:t.passwordNotice_check2)??"Losing this password may result in permanent loss of access to my account and all associated data.",check3:(t==null?void 0:t.passwordNotice_check3)??"No third party, including the support team, can recover or reset this password on my behalf.",nextButton:(t==null?void 0:t.passwordNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.passwordNotice_submitButton)??"I Understand"},n={title:(t==null?void 0:t.passwordSetup_title)??"Create Password",subtitle:(t==null?void 0:t.passwordSetup_subtitle)??"Password is only used to transfer your asset.",newPasswordLabel:(t==null?void 0:t.passwordSetup_newPasswordLabel)??"New Password",confirmPasswordLabel:(t==null?void 0:t.passwordSetup_confirmPasswordLabel)??"Confirm New Password",rule_minLength:(t==null?void 0:t.passwordSetup_rule_minLength)??"Over 8 letters",rule_uppercase:(t==null?void 0:t.passwordSetup_rule_uppercase)??"Include at least 1 uppercase letter",rule_number:(t==null?void 0:t.passwordSetup_rule_number)??"Include at least 1 number",rule_special:(t==null?void 0:t.passwordSetup_rule_special)??"Include at least 1 special character",confirmError:(t==null?void 0:t.passwordSetup_confirmError)??"Password is incorrect",submitButton:(t==null?void 0:t.passwordSetup_submitButton)??"Next"},i=Yo(this.tokens,o),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=p=>{l(),s(p)},u=()=>{l(),s(null)},g=p=>{p.key==="Escape"&&(document.removeEventListener("keydown",g),u())};document.addEventListener("keydown",g);const f=i.querySelector(".__crossx-card");Zo(f,u,()=>{var p;f.innerHTML=jo(n,e),Xo(i,{},d,u),(p=i.querySelector("#__crossx-close-btn"))==null||p.addEventListener("click",u)}),i.addEventListener("click",p=>{p.target===i&&u()})})}showPasswordInputPrompt(e){return new Promise((s,t)=>{ce();const o=this.messages,n=(e==null?void 0:e.verifyMode)===!0,i={title:n?(o==null?void 0:o.verifyPassword_title)??"Verify Your Password":(o==null?void 0:o.passwordInput_title)??"Enter Password",subtitle:n?(o==null?void 0:o.verifyPassword_subtitle)??"To continue, please confirm your current password":(o==null?void 0:o.passwordInput_subtitle)??"Enter your password to continue.",passwordLabel:n?(o==null?void 0:o.verifyPassword_passwordLabel)??"Confirm Password":(o==null?void 0:o.passwordInput_passwordLabel)??"Password",submitButton:(o==null?void 0:o.passwordInput_submitButton)??"Confirm",error:(o==null?void 0:o.passwordInput_error)??"Incorrect password. Please try again."},a=Jo(this.tokens,i,e),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)},u=b=>{d(),s(b)},g=()=>{d(),s(null)},f=b=>{d(),t(b)};Qo(a,u,g,e==null?void 0:e.onSubmit,f),a.addEventListener("click",b=>{b.target===a&&g()});const p=b=>{b.key==="Escape"&&(document.removeEventListener("keydown",p),g())};document.addEventListener("keydown",p)})}showPinInputPrompt(e){return new Promise(s=>{var a;ce();const t=Uo(this.tokens,e);document.body.appendChild(t);const o=()=>t.remove(),n=c=>{o(),s(c)},i=()=>{o(),s(null)};en(t,n,i),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",i),t.addEventListener("click",c=>{c.target===t&&i()})})}showPinLockedPrompt(e,s){return new Promise(t=>{var l;ce();const{overlay:o,startCountdown:n}=Fo(this.tokens,e,s);document.body.appendChild(o);const i=()=>{c(),o.remove()},a=()=>{i(),t()},c=n(a);(l=o.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),o.addEventListener("click",d=>{d.target===o&&a()})})}showTransactionComplete(e){return new Promise(s=>{var a,c;ce();const t=Co(e,this.tokens);document.body.appendChild(t);const o=()=>t.remove(),n=()=>{o(),s()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",n),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",n),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var g;d.stopPropagation();const u=l.dataset.copy;u&&((g=navigator.clipboard)==null||g.writeText(u).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&n()});const i=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",i),n())};document.addEventListener("keydown",i)})}showTransactionProgress(e,s){return new Promise(t=>{ce();const o=ko(e,this.tokens);document.body.appendChild(o);const n=()=>o.remove();let i=!1;const a=()=>{i||(i=!0,n(),t())},c=()=>{var d,u;(d=o.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(u=o.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",a),o.addEventListener("click",g=>{g.target===o&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};s.then(l=>{i||(Ro(o,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(s=>{var c,l,d;ce();let t;e.type==="sign-message"?t=Po(e,this.tokens):e.type==="sign-typed-data"?t=Oo(e,this.tokens):e.type==="sign"?t=Eo(e,this.tokens):t=Io(e,this.tokens),document.body.appendChild(t);const o=()=>t.remove(),n=()=>{o(),s(!0)},i=()=>{o(),s(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",n),(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(u=>{u.addEventListener("click",g=>{var p;g.stopPropagation();const f=u.dataset.copy;f&&((p=navigator.clipboard)==null||p.writeText(f).catch(()=>{}))})}),t.addEventListener("click",u=>{u.target===t&&i()});const a=u=>{u.key==="Escape"&&(document.removeEventListener("keydown",a),i())};document.addEventListener("keydown",a)})}}class sn{constructor(){this._accessToken=null}set(e){this._accessToken=e}get(){return this._accessToken}clear(){this._accessToken=null}has(){return this._accessToken!==null}}function rn(r){r.debug;const e=Fe.production,s={...r,oauthServiceUrl:e.oauthServiceUrl,authApiUrl:e.authApiUrl,walletGatewayUrl:e.walletGatewayUrl},t={gatewayUrl:e.walletGatewayUrl,projectId:r.projectId},n=s.authMode!=="cookie"&&Pt.isAvailable()?new Pt:new sr,i=new uo,a=new fo,c=new wt,l=new sn,d=new Qt;let u;r.useMockWallet?(h.log("[CROSSx] Mock Wallet Provider 사용"),u=new _o(n,d)):(h.log("[CROSSx] Remote Wallet Provider 사용"),u=new Ke(t,n,a,l,d));const g=new Pe(t,a),f=new tn(r.theme??"light",r.themeTokens);return new Ge(s,t,n,i,a,c,u,l,f,g,d)}exports.CROSSxError=m;exports.CROSSxEthereumProvider=Xt;exports.CROSSxSDK=Ge;exports.ChainId=Ds;exports.ErrorCode=_;exports.createCROSSxSDK=rn;
|